/*
 *  TCC - Tiny C Compiler
 * 
 *  Copyright (c) 2001-2004 Fabrice Bellard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "tcc.h"

/* This stuff is used by the code generation backend. */

static int ind; /* output code index */
static int loc; /* local variable index */
static Section *cur_text_section; /* current section where function code is generated */
static SValue *vtop;
static Section *symtab_section;
static CType func_vt; /* current function return type (used by return instruction) */
static int func_vc;
static Section *lbounds_section; /* contains local data bound description */
/* Predefined types */
static CType char_pointer_type;
static CType func_old_type;

/* compile with built-in memory and bounds checker */
static int do_bounds_check = 0;

#ifdef TCC_TARGET_I386
#include "i386/i386-gen.c"
#endif

#ifdef TCC_TARGET_ARM
#include "arm-gen.c"
#endif

#ifdef TCC_TARGET_C67
#include "c67-gen.c"
#endif

/* parser */
static struct BufferedFile *file;
static int fch, tok;
static CValue tokc;
static CString tokcstr; /* current parsed string, if any */
/* additional informations about token */
static int tok_flags, next_tok_flags;

static int *macro_ptr, *macro_ptr_allocated;
static int *unget_saved_macro_ptr;
static int unget_saved_buffer[TOK_MAX_SIZE + 1];
static int unget_buffer_enabled;
static int parse_flags;
static Section *text_section, *data_section, *bss_section; /* predefined sections */
#ifdef CONFIG_TCC_ASM
static Section *last_text_section; /* to handle .previous asm directive */
#endif

/* bound check related sections */
static Section *bounds_section; /* contains global data bound description */
/* symbol sections */
static Section *strtab_section;

/* debug sections */
static Section *stab_section, *stabstr_section;

/*
   rsym: return symbol
   anon_sym: anonymous symbol index
*/
static int rsym, anon_sym;
/* expression generation modifiers */
static int const_wanted; /* true if constant wanted */
static int global_expr;  /* true if compound literals must be allocated
                            globally (used during initializers parsing */
static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
static int tok_ident;
static TokenSym **table_ident;
static TokenSym *hash_ident[TOK_HASH_SIZE];
static char token_buf[STRING_MAX_SIZE + 1];
static char *funcname;
static Sym *global_stack, *local_stack;
static Sym *define_stack;
static Sym *global_label_stack, *local_label_stack;
/* symbol allocator */
static Sym *sym_free_first;

static SValue vstack[VSTACK_SIZE];
/* some predefined types */
static CType int_type;
/* true if isid(c) || isnum(st, c) */
static unsigned char isidnum_table[256];

/* compile with debug symbol (and use them if error during execution) */
static int do_debug = 0;

/* display benchmark infos */
#if !defined(LIBTCC)
static int do_bench = 0;
#endif
static int total_lines;
static int total_bytes;

/* use GNU C extensions */
static int gnu_ext = 1;

/* use Tiny C extensions */
static int tcc_ext = 1;

/* max number of callers shown if error */
static int num_callers = 6;
static const char **rt_bound_error_msg;

/********************************************************/

/* we use our own 'finite' function to avoid potential problems with
   non standard math libs */
/* XXX: endianness dependent */
int ieee_finite(TCCState *st, double d)
{
    int *p = (int *)&d;
    return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
}

/* copy a string and truncate it. */
static char *pstrcpy(TCCState *st, char *buf, int buf_size, const char *s)
{
    char *q, *q_end;
    int c;

    if (buf_size > 0) {
        q = buf;
        q_end = buf + buf_size - 1;
        while (q < q_end) {
            c = *s++;
            *q++ = c;
            if (!c) break;
        }
        *q = '\0';
    }
    return buf;
}

/* strcat and truncate. */
static char *pstrcat(TCCState *st, char *buf, int buf_size, const char *s)
{
    int len;
    len = strlen(buf);
    if (len < buf_size) 
        pstrcpy(st,  buf + len, buf_size - len, s);
    return buf;
}

static int strstart(TCCState *st, const char *str, const char *val, const char **ptr)
{
    const char *p, *q;
    p = str;
    q = val;
    while (*q != '\0') {
        if (*p != *q)
            return 0;
        p++;
        q++;
    }
    if (ptr)
        *ptr = p;
    return 1;
}

static void *tcc_malloc(TCCState *st, unsigned long size)
{
    void *ptr = attemptckalloc(size);
    if (!ptr && size)tcc_error(st, "memory full");
    return ptr;
}

static void *tcc_mallocz(TCCState *st, unsigned long size)
{
    void *ptr;
    ptr = tcc_malloc(st, size);
    memset(ptr, 0, size);
    return ptr;
}

static inline void *tcc_realloc(TCCState *st, void *ptr, unsigned long size)
{
    void *ptr1 = attemptckrealloc(ptr, size);
    if (!ptr1 && size)tcc_error(st, "memory full");
    return ptr1;
}

static char *tcc_strdup(TCCState *st, const char *str)
{
    char *ptr;
    ptr = tcc_malloc(st, strlen(str) + 1);
    strcpy(ptr, str);
    return ptr;
}

#define malloc(s) ckalloc(s)

static void dynarray_add(TCCState *st, void ***ptab, int *nb_ptr, void *data)
{
    int nb, nb_alloc;
    void **pp;
    
    nb = *nb_ptr;
    pp = *ptab;
    /* every power of two we double array size */
    if ((nb & (nb - 1)) == 0) {
        if (!nb)
            nb_alloc = 1;
        else
            nb_alloc = nb * 2;
        pp = tcc_realloc(st, pp, nb_alloc * sizeof(void *));
        if (!pp)
           tcc_error(st, "memory full");
        *ptab = pp;
    }
    pp[nb++] = data;
    *nb_ptr = nb;
}

/* symbol allocator */
static Sym *__sym_malloc(TCCState *st)
{
    Sym *sym_pool, *sym, *last_sym;
    int i;

    sym_pool = tcc_malloc(st, SYM_POOL_NB * sizeof(Sym));

    last_sym = sym_free_first;
    sym = sym_pool;
    for(i = 0; i < SYM_POOL_NB; i++) {
        sym->next = last_sym;
        last_sym = sym;
        sym++;
    }
    sym_free_first = last_sym;
    return last_sym;
}

static inline Sym *sym_malloc(TCCState * st)
{
    Sym *sym;
    sym = sym_free_first;
    if (!sym)
        sym = __sym_malloc(st);
    sym_free_first = sym->next;
    return sym;
}

static inline void sym_free(TCCState *st, Sym *sym)
{
    sym->next = sym_free_first;
    sym_free_first = sym;
}

Section *new_section(TCCState *st, const char *name, int sh_type, int sh_flags)
{
    Section *sec;

    sec = tcc_mallocz(st,sizeof(Section) + strlen(name));
    strcpy(sec->name, name);
    sec->sh_type = sh_type;
    sec->sh_flags = sh_flags;
    switch(sh_type) {
    case SHT_HASH:
    case SHT_REL:
    case SHT_DYNSYM:
    case SHT_SYMTAB:
    case SHT_DYNAMIC:
        sec->sh_addralign = 4;
        break;
    case SHT_STRTAB:
        sec->sh_addralign = 1;
        break;
    default:
        sec->sh_addralign = 32; /* default conservative alignment */
        break;
    }

    /* only add section if not private */
    if (!(sh_flags & SHF_PRIVATE)) {
        sec->sh_num = st->nb_sections;
        dynarray_add(st, (void ***)&st->sections, &st->nb_sections, sec);
    }
    return sec;
}

static void free_section(TCCState *st, Section *s)
{
    ckfree((char *)(s->data));
    ckfree((char *)s);
}

/* realloc section and set its content to zero */
static void section_realloc(TCCState * st, Section *sec, unsigned long new_size)
{
    unsigned long size;
    unsigned char *data;
    
    size = sec->data_allocated;
    if (size == 0)
        size = 1;
    while (size < new_size)
        size = size * 2;
    data = tcc_realloc(st, sec->data, size);
    if (!data)
       tcc_error(st, "memory full");
    memset(data + sec->data_allocated, 0, size - sec->data_allocated);
    sec->data = data;
    sec->data_allocated = size;
}

/* reserve at least 'size' bytes in section 'sec' from
   sec->data_offset. */
static void *section_ptr_add(TCCState *st, Section *sec, unsigned long size)
{
    unsigned long offset, offset1;

    offset = sec->data_offset;
    offset1 = offset + size;
    if (offset1 > sec->data_allocated)
        section_realloc(st, sec, offset1);
    sec->data_offset = offset1;
    return sec->data + offset;
}

/* return a reference to a section, and create it if it does not
   exists */
Section *find_section(TCCState *st, const char *name)
{
    Section *sec;
    int i;
    for(i = 1; i < st->nb_sections; i++) {
        sec = st->sections[i];
        if (!strcmp(name, sec->name)) 
            return sec;
    }
    /* sections are created as PROGBITS */
    return new_section(st, name, SHT_PROGBITS, SHF_ALLOC);
}

#define SECTION_ABS ((void *)1)

/* update sym->c so that it points to an external symbol in section
   'section' with value 'value' */
static void put_extern_sym2(TCCState * st, Sym *sym, Section *section, 
                            unsigned long value, unsigned long size,
                            int can_add_underscore)
{
    int sym_type, sym_bind, sh_num, info;
    Elf32_Sym *esym;
    const char *name;
    char buf1[256];

    if (section == NULL)
        sh_num = SHN_UNDEF;
    else if (section == SECTION_ABS) 
        sh_num = SHN_ABS;
    else
        sh_num = section->sh_num;
    if (!sym->c) {
        if ((sym->type.t & VT_BTYPE) == VT_FUNC)
            sym_type = STT_FUNC;
        else
            sym_type = STT_OBJECT;
        if (sym->type.t & VT_STATIC)
            sym_bind = STB_LOCAL;
        else
            sym_bind = STB_GLOBAL;
        
        name = get_tok_str(st, sym->v, NULL);
#if 0
        if (do_bounds_check) {
            char buf[32];

            /* XXX: avoid doing that for statics ? */
            /* if bound checking is activated, we change some function
               names by adding the "__bound" prefix */
            switch(sym->v) {
#if 0
            /* XXX: we rely only on malloc hooks */
            case TOK_malloc: 
            case TOK_free: 
            case TOK_realloc: 
            case TOK_memalign: 
            case TOK_calloc: 
#endif
            case TOK_memcpy: 
            case TOK_memmove:
            case TOK_memset:
            case TOK_strlen:
            case TOK_strcpy:
            case TOK_alloca:
                strcpy(buf, "__bound_");
                strcat(buf, name);
                name = buf;
                break;
            }
        }
#endif
        if (st->leading_underscore && can_add_underscore) {
            buf1[0] = '_';
            pstrcpy(st,  buf1 + 1, sizeof(buf1) - 1, name);
            name = buf1;
        }
        info = ELF32_ST_INFO(sym_bind, sym_type);
        sym->c = add_elf_sym(st, symtab_section, value, size, info, 0, sh_num, name);
    } else {
        esym = &((Elf32_Sym *)symtab_section->data)[sym->c];
        esym->st_value = value;
        esym->st_size = size;
        esym->st_shndx = sh_num;
    }
}

static void put_extern_sym(TCCState * st, Sym *sym, Section *section, 
                           unsigned long value, unsigned long size)
{
    put_extern_sym2(st, sym, section, value, size, 1);
}

/* add a new relocation entry to symbol 'sym' in section 's' */
static void greloc(TCCState * st, Section *s, Sym *sym, unsigned long offset, int type)
{
    if (!sym->c) 
        put_extern_sym(st, sym, NULL, 0, 0);
    /* now we can add ELF relocation info */
    put_elf_reloc(st, symtab_section, s, offset, type, sym->c);
}

static inline int isid(TCCState *st, int c)
{
    return (c >= 'a' && c <= 'z') ||
        (c >= 'A' && c <= 'Z') ||
        c == '_';
}

static inline int isnum(TCCState *st, int c)
{
    return c >= '0' && c <= '9';
}

static inline int isoct(TCCState *st, int c)
{
    return c >= '0' && c <= '7';
}

static inline int toup(TCCState *st, int c)
{
    if (c >= 'a' && c <= 'z')
        return c - 'a' + 'A';
    else
        return c;
}

static void strcat_vprintf(TCCState *st, char *buf, int buf_size, const char *fmt, va_list ap)
{
    int len;
    len = strlen(buf);
    vsnprintf(buf + len, buf_size - len, fmt, ap);
}

static void strcat_printf(TCCState *st, char *buf, int buf_size, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    strcat_vprintf(st, buf, buf_size, fmt, ap);
    va_end(ap);
}

void error1(TCCState *st, int is_warning, const char *fmt, va_list ap)
{
    char buf[2048];
    BufferedFile **f;
    
    buf[0] = '\0';
    if (file) {
        for(f = st->include_stack; f < st->include_stack_ptr; f++)
            strcat_printf(st, buf, sizeof(buf), "In file included from %s:%d:\n", 
                          (*f)->filename, (*f)->line_num);
        if (file->line_num > 0) {
            strcat_printf(st, buf, sizeof(buf), 
                          "%s:%d: ", file->filename, file->line_num);
        } else {
            strcat_printf(st, buf, sizeof(buf),
                          "%s: ", file->filename);
        }
    } else {
        strcat_printf(st, buf, sizeof(buf),
                      "tcc: ");
    }
    if (is_warning)
        strcat_printf(st, buf, sizeof(buf), "warning: ");
    strcat_vprintf(st, buf, sizeof(buf), fmt, ap);

    if (!st->error_func) {
        /* default case: stderr */
        fprintf(stderr, "%s\n", buf);
    } else {
        st->error_func(st->error_opaque, buf);
    }
    if (!is_warning || st->warn_error)
        st->nb_errors++;
}

#ifdef LIBTCC
void tcc_set_error_func(TCCState *s, void *error_opaque,
                        void (*error_func)(void *opaque, const char *msg))
{
    s->error_opaque = error_opaque;
    s->error_func = error_func;
}
#endif

/* error without aborting current compilation */
void error_noabort(TCCState * st, const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    error1(st, 0, fmt, ap);
    va_end(ap);
}

void tcc_error(TCCState * st, const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    error1(st, 0, fmt, ap);
    va_end(ap);
    /* better than nothing: in some cases, we accept to handle errors */
    if (st->error_set_jmp_enabled) {
        longjmp(st->error_jmp_buf, 1);
    } else {
        /* XXX: eliminate this someday */
        exit(1);
    }
}

void expect(TCCState * st, const char *msg)
{
   tcc_error(st, "%s expected", msg);
}

void warning(TCCState * st, const char *fmt, ...)
{
    va_list ap;

    if (st->warn_none)
        return;

    va_start(ap, fmt);
    error1(st, 1, fmt, ap);
    va_end(ap);
}

void skip(TCCState *st, int c)
{
    if (tok != c)
       tcc_error(st,"'%c' expected", c);
    next(st);
}

static void test_lvalue(TCCState *st)
{
    if (!(vtop->r & VT_LVAL))
        expect(st, "lvalue");
}

/* allocate a new token */
static TokenSym *tok_alloc_new(TCCState *st, TokenSym **pts, const char *str, int len)
{
    TokenSym *ts, **ptable;
    int i;

    if (tok_ident >= SYM_FIRST_ANOM) 
       tcc_error(st, "memory full");

    /* expand token table if needed */
    i = tok_ident - TOK_IDENT;
    if ((i % TOK_ALLOC_INCR) == 0) {
        ptable = tcc_realloc(st, table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
        if (!ptable)
           tcc_error(st, "memory full");
        table_ident = ptable;
    }

    ts = tcc_malloc(st, sizeof(TokenSym) + len);
    table_ident[i] = ts;
    ts->tok = tok_ident++;
    ts->sym_define = NULL;
    ts->sym_label = NULL;
    ts->sym_struct = NULL;
    ts->sym_identifier = NULL;
    ts->len = len;
    ts->hash_next = NULL;
    memcpy(ts->str, str, len);
    ts->str[len] = '\0';
    *pts = ts;
    return ts;
}

#define TOK_HASH_INIT 1
#define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))

/* find a token and add it if not found */
static TokenSym *tok_alloc(TCCState *st, const char *str, int len)
{
    TokenSym *ts, **pts;
    int i;
    unsigned int h;
    
    h = TOK_HASH_INIT;
    for(i=0;i<len;i++)
        h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
    h &= (TOK_HASH_SIZE - 1);

    pts = &hash_ident[h];
    for(;;) {
        ts = *pts;
        if (!ts)
            break;
        if (ts->len == len && !memcmp(ts->str, str, len))
            return ts;
        pts = &(ts->hash_next);
    }
    return tok_alloc_new(st, pts, str, len);
}

/* CString handling */

static void cstr_realloc(TCCState *st, CString *cstr, int new_size)
{
    int size;
    void *data;

    size = cstr->size_allocated;
    if (size == 0)
        size = 8; /* no need to allocate a too small first string */
    while (size < new_size)
        size = size * 2;
    data = tcc_realloc(st, cstr->data_allocated, size);
    if (!data)
       tcc_error(st, "memory full");
    cstr->data_allocated = data;
    cstr->size_allocated = size;
    cstr->data = data;
}

/* add a byte */
static inline void cstr_ccat(TCCState *st,CString *cstr, int ch)
{
    int size;
    size = cstr->size + 1;
    if (size > cstr->size_allocated)
        cstr_realloc(st, cstr, size);
    ((unsigned char *)cstr->data)[size - 1] = ch;
    cstr->size = size;
}

static void cstr_cat(TCCState *st, CString *cstr, const char *str)
{
    int c;
    for(;;) {
        c = *str;
        if (c == '\0')
            break;
        cstr_ccat(st, cstr, c);
        str++;
    }
}

/* add a wide char */
static void cstr_wccat(TCCState *st, CString *cstr, int ch)
{
    int size;
    size = cstr->size + sizeof(nwchar_t);
    if (size > cstr->size_allocated)
        cstr_realloc(st, cstr, size);
    *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
    cstr->size = size;
}

static void cstr_new(TCCState *st, CString *cstr)
{
    memset(cstr, 0, sizeof(CString));
}

/* free string and reset it to NULL */
static void cstr_free(TCCState *st, CString *cstr)
{
    ckfree((char *)(cstr->data_allocated));
    cstr_new(st, cstr);
}

#define cstr_reset(ts, cstr) cstr_free(ts, cstr)

/* XXX: unicode ? */
static void add_char(TCCState *st, CString *cstr, int c)
{
    if (c == '\'' || c == '\"' || c == '\\') {
        /* XXX: could be more precise if char or string */
        cstr_ccat(st, cstr, '\\');
    }
    if (c >= 32 && c <= 126) {
        cstr_ccat(st, cstr, c);
    } else {
        cstr_ccat(st, cstr, '\\');
        if (c == '\n') {
            cstr_ccat(st, cstr, 'n');
        } else {
            cstr_ccat(st, cstr, '0' + ((c >> 6) & 7));
            cstr_ccat(st, cstr, '0' + ((c >> 3) & 7));
            cstr_ccat(st, cstr, '0' + (c & 7));
        }
    }
}

/* XXX: buffer overflow */
/* XXX: float tokens */
char *get_tok_str(TCCState *st, int v, CValue *cv)
{
    static char buf[STRING_MAX_SIZE + 1];
    static CString cstr_buf;
    CString *cstr;
    unsigned char *q;
    char *p;
    int i, len;

    /* NOTE: to go faster, we give a fixed buffer for small strings */
    cstr_reset(st, &cstr_buf);
    cstr_buf.data = buf;
    cstr_buf.size_allocated = sizeof(buf);
    p = buf;

    switch(v) {
    case TOK_CINT:
    case TOK_CUINT:
        /* XXX: not quite exact, but only useful for testing */
        sprintf(p, "%u", cv->ui);
        break;
    case TOK_CLLONG:
    case TOK_CULLONG:
        /* XXX: not quite exact, but only useful for testing  */
        sprintf(p, "%Lu", cv->ull);
        break;
    case TOK_CCHAR:
    case TOK_LCHAR:
        cstr_ccat(st, &cstr_buf, '\'');
        add_char(st, &cstr_buf, cv->i);
        cstr_ccat(st, &cstr_buf, '\'');
        cstr_ccat(st, &cstr_buf, '\0');
        break;
    case TOK_PPNUM:
        cstr = cv->cstr;
        len = cstr->size - 1;
        for(i=0;i<len;i++)
            add_char(st, &cstr_buf, ((unsigned char *)cstr->data)[i]);
        cstr_ccat(st, &cstr_buf, '\0');
        break;
    case TOK_STR:
    case TOK_LSTR:
        cstr = cv->cstr;
        cstr_ccat(st, &cstr_buf, '\"');
        if (v == TOK_STR) {
            len = cstr->size - 1;
            for(i=0;i<len;i++)
                add_char(st, &cstr_buf, ((unsigned char *)cstr->data)[i]);
        } else {
            len = (cstr->size / sizeof(nwchar_t)) - 1;
            for(i=0;i<len;i++)
                add_char(st, &cstr_buf, ((nwchar_t *)cstr->data)[i]);
        }
        cstr_ccat(st, &cstr_buf, '\"');
        cstr_ccat(st, &cstr_buf, '\0');
        break;
    case TOK_LT:
        v = '<';
        goto addv;
    case TOK_GT:
        v = '>';
        goto addv;
    case TOK_DOTS:
        return strcpy(p, "...");
    case TOK_A_SHL:
        return strcpy(p, "<<=");
    case TOK_A_SAR:
        return strcpy(p, ">>=");
    default:
        if (v < TOK_IDENT) {
            /* search in two bytes table */
            q = tok_two_chars;
            while (*q) {
                if (q[2] == v) {
                    *p++ = q[0];
                    *p++ = q[1];
                    *p = '\0';
                    return buf;
                }
                q += 3;
            }
        addv:
            *p++ = v;
            *p = '\0';
        } else if (v < tok_ident) {
            return table_ident[v - TOK_IDENT]->str;
        } else if (v >= SYM_FIRST_ANOM) {
            /* special name for anonymous symbol */
            sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
        } else {
            /* should never happen */
            return NULL;
        }
        break;
    }
    return cstr_buf.data;
}

/* push, without hashing */
static Sym *sym_push2(TCCState *st, Sym **ps, int v, int t, int c)
{
    Sym *s;
    s = sym_malloc(st);
    s->v = v;
    s->type.t = t;
    s->c = c;
    s->next = NULL;
    /* add in stack */
    s->prev = *ps;
    *ps = s;
    return s;
}

/* find a symbol and return its associated structure. 's' is the top
   of the symbol stack */
static Sym *sym_find2(TCCState *st, Sym *s, int v)
{
    while (s) {
        if (s->v == v)
            return s;
        s = s->prev;
    }
    return NULL;
}

/* structure lookup */
static inline Sym *struct_find(TCCState *st, int v)
{
    v -= TOK_IDENT;
    if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
        return NULL;
    return table_ident[v]->sym_struct;
}

/* find an identifier */
static inline Sym *sym_find(TCCState *st, int v)
{
    v -= TOK_IDENT;
    if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
        return NULL;
    return table_ident[v]->sym_identifier;
}

/* push a given symbol on the symbol stack */
static Sym *sym_push(TCCState *st, int v, CType *type, int r, int c)
{
    Sym *s, **ps;
    TokenSym *ts;

    if (local_stack)
        ps = &local_stack;
    else
        ps = &global_stack;
    s = sym_push2(st, ps, v, type->t, c);
    s->type.ref = type->ref;
    s->r = r;
    /* don't record fields or anonymous symbols */
    /* XXX: simplify */
    if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
        /* record symbol in token array */
        ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
        if (v & SYM_STRUCT)
            ps = &ts->sym_struct;
        else
            ps = &ts->sym_identifier;
        s->prev_tok = *ps;
        *ps = s;
    }
    return s;
}

/* push a global identifier */
static Sym *global_identifier_push(TCCState *st, int v, int t, int c)
{
    Sym *s, **ps;
    s = sym_push2(st, &global_stack, v, t, c);
    /* don't record anonymous symbol */
    if (v < SYM_FIRST_ANOM) {
        ps = &table_ident[v - TOK_IDENT]->sym_identifier;
        /* modify the top most local identifier, so that
           sym_identifier will point to 's' when popped */
        while (*ps != NULL)
            ps = &(*ps)->prev_tok;
        s->prev_tok = NULL;
        *ps = s;
    }
    return s;
}

/* pop symbols until top reaches 'b' */
static void sym_pop(TCCState *st, Sym **ptop, Sym *b)
{
    Sym *s, *ss, **ps;
    TokenSym *ts;
    int v;

    s = *ptop;
    while(s != b) {
        ss = s->prev;
        v = s->v;
        /* remove symbol in token array */
        /* XXX: simplify */
        if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
            ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
            if (v & SYM_STRUCT)
                ps = &ts->sym_struct;
            else
                ps = &ts->sym_identifier;
            *ps = s->prev_tok;
        }
        sym_free(st, s);
        s = ss;
    }
    *ptop = b;
}

/* I/O layer */

BufferedFile *tcc_open(TCCState *st, const char *filename)
{
    Tcl_Channel fd;
    BufferedFile *bf;
    int i, len;
    /*printf("opening '%s'\n", filename); */
    Tcl_Obj * path ;
    path = Tcl_NewStringObj(filename,-1);
    Tcl_IncrRefCount(path);
    fd = Tcl_FSOpenFileChannel(NULL,path, "r", 0);
    Tcl_DecrRefCount(path);
    if (fd==NULL) {
        /*printf("T_FOFC, returned NULL\n");  */
        return NULL;
    }
    /*printf("T_FOFC, returned SUCCESS\n");  */
    bf = tcc_malloc(st, sizeof(BufferedFile));
    if (!bf) {
        Tcl_Close(NULL,fd);
        return NULL;
    }
    bf->fd = fd;
    bf->buf_ptr = bf->buffer;
    bf->buf_end = bf->buffer;
    bf->buffer[0] = CH_EOB; /* put eob symbol */
    pstrcpy(st,  bf->filename, sizeof(bf->filename), filename);
    len = strlen(bf->filename);
    for (i = 0; i < len; i++)
        if (bf->filename[i] == '\\')
            bf->filename[i] = '/';
    bf->line_num = 1;
    bf->ifndef_macro = 0;
    bf->ifdef_stack_ptr = st->ifdef_stack_ptr;
    return bf;
}

void tcc_close(BufferedFile *bf)
{
    total_lines += bf->line_num;
    Tcl_Close(NULL,bf->fd);
    ckfree((char *)bf);
}

/* fill input buffer and peek next char */
static int tcc_peekc_slow(TCCState *st, BufferedFile *bf)
{
    int len;
    /* only tries to read if really end of buffer */
    if (bf->buf_ptr >= bf->buf_end) {
        if (bf->fd != NULL) {
#if defined(PARSE_DEBUG)
            len = 8;
#else
            len = IO_BUF_SIZE;
#endif
            len = Tcl_Read(bf->fd, bf->buffer, len);
            if (len < 0)
                len = 0;
        } else {
            len = 0;
        }
        total_bytes += len;
        bf->buf_ptr = bf->buffer;
        bf->buf_end = bf->buffer + len;
        *bf->buf_end = CH_EOB;
    }
    if (bf->buf_ptr < bf->buf_end) {
        return bf->buf_ptr[0];
    } else {
        bf->buf_ptr = bf->buf_end;
        return CH_EOF;
    }
}

/* return the current character, handling end of block if necessary
   (but not stray) */
static int handle_eob(TCCState *st)
{
    return tcc_peekc_slow(st, file);
}

/* read next char from current input file and handle end of input buffer */
static inline void inp(TCCState *st)
{
    fch = *(++(file->buf_ptr));
    /* end of buffer/file handling */
    if (fch == CH_EOB)
        fch = handle_eob(st);
}

/* space excluding newline */
static inline int is_space(TCCState *st, int ch)
{
    return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
}

/* handle '\[\r]\n' */
static int handle_stray_noerror(TCCState *st)
{
    while (fch == '\\') {
        inp(st);
        while (is_space(st, fch)) inp(st);
        if (fch == '\n') {
            file->line_num++;
            inp(st);
        } else return 1;
    }
    return 0;
}

static void handle_stray(TCCState *st)
{
    if(handle_stray_noerror(st))
       tcc_error(st, "stray '\\' in program");
}

/* skip the stray and handle the \\n case. Output an error if
   incorrect char after the stray */
static int handle_stray1(TCCState *st, uint8_t *p)
{
    int c;

    if (p >= file->buf_end) {
        file->buf_ptr = p;
        c = handle_eob(st);
        p = file->buf_ptr;
        if (c == '\\')
            goto parse_stray;
    } else {
    parse_stray:
        file->buf_ptr = p;
        fch = *p;
        handle_stray(st);
        p = file->buf_ptr;
        c = *p;
    }
    return c;
}

/* handle just the EOB case, but not stray */
#define PEEKC_EOB(st, c, p)\
{\
    p++;\
    c = *p;\
    if (c == '\\') {\
        file->buf_ptr = p;\
        c = handle_eob(st);\
        p = file->buf_ptr;\
    }\
}

/* handle the complicated stray case */
#define PEEKC(st, c, p)\
{\
    p++;\
    c = *p;\
    if (c == '\\') {\
        c = handle_stray1(st, p);\
        p = file->buf_ptr;\
    }\
}

/* input with '\[\r]\n' handling. Note that this function cannot
   handle other characters after '\', so you cannot call it inside
   strings or comments */
static void minp(TCCState *st)
{
    inp(st);
    if (fch == '\\') 
        handle_stray(st);
}


/* single line C++ comments */
static uint8_t *parse_line_comment(TCCState *st, uint8_t *p)
{
    int c;

    p++;
    for(;;) {
        c = *p;
    redo:
        if (c == '\n' || c == CH_EOF) {
            break;
        } else if (c == '\\') {
            file->buf_ptr = p;
            c = handle_eob(st);
            p = file->buf_ptr;
            if (c == '\\') {
                PEEKC_EOB(st, c, p);
                if (c == '\n') {
                    file->line_num++;
                    PEEKC_EOB(st, c, p);
                } else if (c == '\r') {
                    PEEKC_EOB(st, c, p);
                    if (c == '\n') {
                        file->line_num++;
                        PEEKC_EOB(st, c, p);
                    }
                }
            } else {
                goto redo;
            }
        } else {
            p++;
        }
    }
    return p;
}

/* C comments */
static uint8_t *parse_comment(TCCState *st, uint8_t *p)
{
    int c;
    
    p++;
    for(;;) {
        /* fast skip loop */
        for(;;) {
            c = *p;
            if (c == '\n' || c == '*' || c == '\\')
                break;
            p++;
            c = *p;
            if (c == '\n' || c == '*' || c == '\\')
                break;
            p++;
        }
        /* now we can handle all the cases */
        if (c == '\n') {
            file->line_num++;
            p++;
        } else if (c == '*') {
            p++;
            for(;;) {
                c = *p;
                if (c == '*') {
                    p++;
                } else if (c == '/') {
                    goto end_of_comment;
                } else if (c == '\\') {
                    file->buf_ptr = p;
                    c = handle_eob(st);
                    p = file->buf_ptr;
                    if (c == '\\') {
                        /* skip '\[\r]\n', otherwise just skip the stray */
                        while (c == '\\') {
                            PEEKC_EOB(st, c, p);
                            if (c == '\n') {
                                file->line_num++;
                                PEEKC_EOB(st, c, p);
                            } else if (c == '\r') {
                                PEEKC_EOB(st, c, p);
                                if (c == '\n') {
                                    file->line_num++;
                                    PEEKC_EOB(st, c, p);
                                }
                            } else {
                                goto after_star;
                            }
                        }
                    }
                } else {
                    break;
                }
            }
        after_star: ;
        } else {
            /* stray, eob or eof */
            file->buf_ptr = p;
            c = handle_eob(st);
            p = file->buf_ptr;
            if (c == CH_EOF) {
               tcc_error(st, "unexpected end of file in comment");
            } else if (c == '\\') {
                p++;
            }
        }
    }
 end_of_comment:
    p++;
    return p;
}

#define cinp minp

static inline void skip_spaces(TCCState *st)
{
    while (is_space(st, fch))
        cinp(st);
}

/* parse a string without interpreting escapes */
static uint8_t *parse_pp_string(TCCState *st, uint8_t *p,
                                int sep, CString *str)
{
    int c;
    p++;
    for(;;) {
        c = *p;
        if (c == sep) {
            break;
        } else if (c == '\\') {
            file->buf_ptr = p;
            c = handle_eob(st);
            p = file->buf_ptr;
            if (c == CH_EOF) {
            unterminated_string:
                /* XXX: indicate line number of start of string */
               tcc_error(st, "missing terminating %c character", sep);
            } else if (c == '\\') {
                /* escape : just skip \[\r]\n */
                PEEKC_EOB(st, c, p);
                if (c == '\n') {
                    file->line_num++;
                    p++;
                } else if (c == '\r') {
                    PEEKC_EOB(st, c, p);
                    if (c != '\n')
                        expect(st, "'\n' after '\r'");
                    file->line_num++;
                    p++;
                } else if (c == CH_EOF) {
                    goto unterminated_string;
                } else {
                    if (str) {
                        cstr_ccat(st, str, '\\');
                        cstr_ccat(st, str, c);
                    }
                    p++;
                }
            }
        } else if (c == '\n') {
            file->line_num++;
            goto add_char;
        } else if (c == '\r') {
            PEEKC_EOB(st, c, p);
            if (c != '\n') {
                if (str)
                    cstr_ccat(st, str, '\r');
            } else {
                file->line_num++;
                goto add_char;
            }
        } else {
        add_char:
            if (str)
                cstr_ccat(st, str, c);
            p++;
        }
    }
    p++;
    return p;
}

/* skip block of text until #else, #elif or #endif. skip also pairs of
   #if/#endif */
void preprocess_skip(TCCState *st)
{
    int a, start_of_line, c;
    uint8_t *p;

    p = file->buf_ptr;
    start_of_line = 1;
    a = 0;
    for(;;) {
    redo_no_start:
        c = *p;
        switch(c) {
        case ' ':
        case '\t':
        case '\f':
        case '\v':
        case '\r':
            p++;
            goto redo_no_start;
        case '\n':
            start_of_line = 1;
            file->line_num++;
            p++;
            goto redo_no_start;
        case '\\':
            file->buf_ptr = p;
            c = handle_eob(st);
            if (c == CH_EOF) {
                expect(st, "#endif");
            } else if (c == '\\') {
                fch = file->buf_ptr[0];
                handle_stray_noerror(st);
            }
            p = file->buf_ptr;
            goto redo_no_start;
            /* skip strings */
        case '\"':
        case '\'':
            p = parse_pp_string(st, p, c, NULL);
            break;
            /* skip comments */
        case '/':
            file->buf_ptr = p;
            fch = *p;
            minp(st);
            p = file->buf_ptr;
            if (fch == '*') {
                p = parse_comment(st, p);
            } else if (fch == '/') {
                p = parse_line_comment(st, p);
            }
            break;

        case '#':
            p++;
            if (start_of_line) {
                file->buf_ptr = p;
                next_nomacro(st);
                p = file->buf_ptr;
                if (a == 0 && 
                    (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
                    goto the_end;
                if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
                    a++;
                else if (tok == TOK_ENDIF)
                    a--;
            }
            break;
        default:
            p++;
            break;
        }
        start_of_line = 0;
    }
 the_end: ;
    file->buf_ptr = p;
}

/* ParseState handling */

/* XXX: currently, no include file info is stored. Thus, we cannot display
   accurate messages if the function or data definition spans multiple
   files */

/* save current parse state in 's' */
void save_parse_state(TCCState *st, ParseState *s)
{
    s->line_num = file->line_num;
    s->macro_ptr = macro_ptr;
    s->tok = tok;
    s->tokc = tokc;
}

/* restore parse state from 's' */
void restore_parse_state(TCCState *st, ParseState *s)
{
    file->line_num = s->line_num;
    macro_ptr = s->macro_ptr;
    tok = s->tok;
    tokc = s->tokc;
}

/* return the number of additional 'ints' necessary to store the
   token */
static inline int tok_ext_size(TCCState *st, int t)
{
    switch(t) {
        /* 4 bytes */
    case TOK_CINT:
    case TOK_CUINT:
    case TOK_CCHAR:
    case TOK_LCHAR:
    case TOK_CFLOAT:
    case TOK_LINENUM:
        return 1;
    case TOK_STR:
    case TOK_LSTR:
    case TOK_PPNUM:
       tcc_error(st,"unsupported token");
        return 1;
    case TOK_CDOUBLE:
    case TOK_CLLONG:
    case TOK_CULLONG:
        return 2;
    case TOK_CLDOUBLE:
        return LDOUBLE_SIZE / 4;
    default:
        return 0;
    }
}

/* token string handling */

static inline void tok_str_new(TCCState *st, TokenString *s)
{
    s->str = NULL;
    s->len = 0;
    s->allocated_len = 0;
    s->last_line_num = -1;
}

static void tok_str_free(TCCState *st, int *str)
{
    ckfree((char *)str);
}

static int *tok_str_realloc(TCCState *st, TokenString *s)
{
    int *str, len;

    if (s->allocated_len == 0) {
        len = 8;
    } else {
        len = s->allocated_len * 2;
    }
    str = tcc_realloc(st, s->str, len * sizeof(int));
    if (!str)
       tcc_error(st, "memory full");
    s->allocated_len = len;
    s->str = str;
    return str;
}

static void tok_str_add(TCCState *st, TokenString *s, int t, int tf)
{
    int len, *str;

    len = s->len;
    str = s->str;
    if (len+1 >= s->allocated_len)
        str = tok_str_realloc(st, s);
    str[len++] = t;
    str[len++] = tf;
    s->len = len;
}

static void tok_str_add2(TCCState *st, TokenString *s, int t, int tf, CValue *cv)
{
    int len, *str;

    len = s->len;
    str = s->str;

    /* allocate space for worst case */
    if (len + TOK_MAX_SIZE > s->allocated_len)
        str = tok_str_realloc(st, s);
    str[len++] = t;
    str[len++] = tf;
    switch(t) {
    case TOK_CINT:
    case TOK_CUINT:
    case TOK_CCHAR:
    case TOK_LCHAR:
    case TOK_CFLOAT:
    case TOK_LINENUM:
        str[len++] = cv->tab[0];
        break;
    case TOK_PPNUM:
    case TOK_STR:
    case TOK_LSTR:
        {
            int nb_words;
            CString *cstr;

            nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
            while ((len + nb_words) > s->allocated_len)
                str = tok_str_realloc(st, s);
            cstr = (CString *)(str + len);
            cstr->data = NULL;
            cstr->size = cv->cstr->size;
            cstr->data_allocated = NULL;
            cstr->size_allocated = cstr->size;
            memcpy((char *)cstr + sizeof(CString), 
                   cv->cstr->data, cstr->size);
            len += nb_words;
        }
        break;
    case TOK_CDOUBLE:
    case TOK_CLLONG:
    case TOK_CULLONG:
#if LDOUBLE_SIZE == 8
    case TOK_CLDOUBLE:
#endif
        str[len++] = cv->tab[0];
        str[len++] = cv->tab[1];
        break;
#if LDOUBLE_SIZE == 12
    case TOK_CLDOUBLE:
        str[len++] = cv->tab[0];
        str[len++] = cv->tab[1];
        str[len++] = cv->tab[2];
#elif LDOUBLE_SIZE != 8
#error add long double size support
#endif
        break;
    default:
        break;
    }
    s->len = len;
}

/* add the current parse token in token string 's' */
static void tok_str_add_tok(TCCState *st, TokenString *s)
{
    CValue cval;

    /* save line number info */
    if (file->line_num != s->last_line_num) {
        s->last_line_num = file->line_num;
        cval.i = s->last_line_num;
        tok_str_add2(st, s, TOK_LINENUM, 0, &cval);
    }
    tok_str_add2(st, s, tok, tok_flags, &tokc);
}

#if LDOUBLE_SIZE == 12
#define LDOUBLE_GET(st, p, cv)                      \
        cv.tab[0] = p[0];                       \
        cv.tab[1] = p[1];                       \
        cv.tab[2] = p[2];
#elif LDOUBLE_SIZE == 8
#define LDOUBLE_GET(st, p, cv)                      \
        cv.tab[0] = p[0];                       \
        cv.tab[1] = p[1];
#else
#error add long double size support
#endif


/* get a token from an integer array and increment pointer
   accordingly. we code it as a macro to avoid pointer aliasing. */
#define TOK_GET(t, tf, p, cv)                   \
{                                               \
    t = *p++;                                   \
    tf = *p++;                                  \
    switch(t) {                                 \
    case TOK_CINT:                              \
    case TOK_CUINT:                             \
    case TOK_CCHAR:                             \
    case TOK_LCHAR:                             \
    case TOK_CFLOAT:                            \
    case TOK_LINENUM:                           \
        cv.tab[0] = *p++;                       \
        break;                                  \
    case TOK_STR:                               \
    case TOK_LSTR:                              \
    case TOK_PPNUM:                             \
        cv.cstr = (CString *)p;                 \
        cv.cstr->data = (char *)p + sizeof(CString);\
        p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
        break;                                  \
    case TOK_CDOUBLE:                           \
    case TOK_CLLONG:                            \
    case TOK_CULLONG:                           \
        cv.tab[0] = p[0];                       \
        cv.tab[1] = p[1];                       \
        p += 2;                                 \
        break;                                  \
    case TOK_CLDOUBLE:                          \
        LDOUBLE_GET(st, p, cv);                     \
        p += LDOUBLE_SIZE / 4;                  \
        break;                                  \
    default:                                    \
        break;                                  \
    }                                           \
}

/* defines handling */
static inline void define_push(TCCState *st, int v, int macro_type, int *str, Sym *first_arg)
{
    Sym *s;

    s = sym_push2(st, &define_stack, v, macro_type, (int)str);
    s->next = first_arg;
    table_ident[v - TOK_IDENT]->sym_define = s;
}

/* undefined a define symbol. Its name is just set to zero */
static void define_undef(Sym *s)
{
    int v;
    v = s->v;
    if (v >= TOK_IDENT && v < tok_ident)
        table_ident[v - TOK_IDENT]->sym_define = NULL;
    s->v = 0;
}

static inline Sym *define_find(TCCState *st, int v)
{
    v -= TOK_IDENT;
    if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
        return NULL;
    return table_ident[v]->sym_define;
}

/* free define stack until top reaches 'b' */
static void free_defines(TCCState *st, Sym *b)
{
    Sym *top, *top1;
    int v;

    top = define_stack;
    while (top != b) {
        top1 = top->prev;
        /* do not free args or predefined defines */
        if (top->c)
            tok_str_free(st, (int *)top->c);
        v = top->v;
        if (v >= TOK_IDENT && v < tok_ident)
            table_ident[v - TOK_IDENT]->sym_define = NULL;
        sym_free(st, top);
        top = top1;
    }
    define_stack = b;
}

/* label lookup */
static Sym *label_find(TCCState *st, int v)
{
    v -= TOK_IDENT;
    if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
        return NULL;
    return table_ident[v]->sym_label;
}

static Sym *label_push(TCCState *st, Sym **ptop, int v, int flags)
{
    Sym *s, **ps;
    s = sym_push2(st, ptop, v, 0, 0);
    s->r = flags;
    ps = &table_ident[v - TOK_IDENT]->sym_label;
    if (ptop == &global_label_stack) {
        /* modify the top most local identifier, so that
           sym_identifier will point to 's' when popped */
        while (*ps != NULL)
            ps = &(*ps)->prev_tok;
    }
    s->prev_tok = *ps;
    *ps = s;
    return s;
}

/* pop labels until element last is reached. Look if any labels are
   undefined. Define symbols if '&&label' was used. */
static void label_pop(TCCState * state, Sym **ptop, Sym *slast)
{
    Sym *s, *st;
    for(s = *ptop; s != slast; s = st) {
        st = s->prev;
        if (s->r == LABEL_DECLARED) {
            warning(state, "label '%s' declared but not used", get_tok_str(state, s->v, NULL));
        } else if (s->r == LABEL_FORWARD) {
               tcc_error(state, "label '%s' used but not defined",
                      get_tok_str(state, s->v, NULL));
        } else {
            if (s->c) {
                /* define corresponding symbol. A size of
                   1 is put. */
                put_extern_sym(state, s, cur_text_section, (long)s->next, 1);
            }
        }
        /* remove label */
        table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
        sym_free(state, s);
    }
    *ptop = slast;
}

/* eval an expression for #if/#elif */
static int expr_preprocess(TCCState *st)
{
    int c, t;
    TokenString str;
    
    tok_str_new(st, &str);
    while (tok != TOK_LINEFEED && tok != TOK_EOF) {
        next(st); /* do macro subst */
        if (tok == TOK_DEFINED) {
            next_nomacro(st);
            t = tok;
            if (t == '(') 
                next_nomacro(st);
            c = define_find(st, tok) != 0;
            if (t == '(')
                next_nomacro(st);
            tok = TOK_CINT;
            tokc.i = c;
        } else if (tok >= TOK_IDENT) {
            /* if undefined macro */
            tok = TOK_CINT;
            tokc.i = 0;
        }
        tok_str_add_tok(st, &str);
    }
    tok_str_add(st, &str, -1, 0); /* simulate end of file */
    tok_str_add(st, &str, 0, 0);
    /* now evaluate C constant expression */
    macro_ptr = str.str;
    next(st);
    c = expr_const(st);
    macro_ptr = NULL;
    tok_str_free(st, str.str);
    return c != 0;
}

#if defined(PARSE_DEBUG) || defined(PP_DEBUG)
static void tok_print(TCCState *st, int *str)
{
    int t, tf;
    CValue cval;

    while (1) {
        TOK_GET(st, t, tf, str, cval);
        if (!t)
            break;
        printf(st, " %s", get_tok_str(st, t, &cval));
    }
    printf("\n");
}
#endif

/* parse after #define */
static void parse_define(TCCState *st)
{
    Sym *s, *first, **ps;
    int v, t, varg, is_vaargs, c;
    TokenString str;
    
    v = tok;
    if (v < TOK_IDENT)
       tcc_error(st, "invalid macro name '%s'", get_tok_str(st, tok, &tokc));
    /* XXX: should check if same macro (ANSI) */
    first = NULL;
    t = MACRO_OBJ;
    /* '(' must be just after macro definition for MACRO_FUNC */
    c = file->buf_ptr[0];
    if (c == '\\')
        c = handle_stray1(st, file->buf_ptr);
    if (c == '(') {
        next_nomacro(st);
        next_nomacro(st);
        ps = &first;
        while (tok != ')') {
            varg = tok;
            next_nomacro(st);
            is_vaargs = 0;
            if (varg == TOK_DOTS) {
                varg = TOK___VA_ARGS__;
                is_vaargs = 1;
            } else if (tok == TOK_DOTS && gnu_ext) {
                is_vaargs = 1;
                next_nomacro(st);
            }
            if (varg < TOK_IDENT)
               tcc_error(st,"badly punctuated parameter list");
            s = sym_push2(st,&define_stack, varg | SYM_FIELD, is_vaargs, 0);
            *ps = s;
            ps = &s->next;
            if (tok != ',')
                break;
            next_nomacro(st);
        }
        t = MACRO_FUNC;
    }
    tok_str_new(st, &str);
    next_nomacro(st);
    /* EOF testing necessary for '-D' handling */
    while (tok != TOK_LINEFEED && tok != TOK_EOF) {
        tok_str_add2(st,&str, tok, tok_flags, &tokc);
        next_nomacro(st);
    }
    tok_str_add(st,&str, 0, 0);
#ifdef PP_DEBUG
    printf("define %s %d: ", get_tok_str(st,v, NULL), t);
    tok_print(st, str.str);
#endif
    define_push(st, v, t, str.str, first);
}

static inline int hash_cached_include(TCCState *st, int type, const char *filename)
{
    const unsigned char *s;
    unsigned int h;

    h = TOK_HASH_INIT;
    h = TOK_HASH_FUNC(h, type);
    s = filename;
    while (*s) {
        h = TOK_HASH_FUNC(h, *s);
        s++;
    }
    h &= (CACHED_INCLUDES_HASH_SIZE - 1);
    return h;
}

/* XXX: use a token or a hash table to accelerate matching ? */
static CachedInclude *search_cached_include(TCCState *st,
                                            int type, const char *filename)
{
    CachedInclude *e;
    int i, h;
    h = hash_cached_include(st, type, filename);
    i = st->cached_includes_hash[h];
    for(;;) {
        if (i == 0)
            break;
        e = st->cached_includes[i - 1];
        if (e->type == type && !strcmp(e->filename, filename))
            return e;
        i = e->hash_next;
    }
    return NULL;
}

static inline void add_cached_include(TCCState *st, int type, 
                                      const char *filename, int ifndef_macro)
{
    CachedInclude *e;
    int h;

    if (search_cached_include(st, type, filename))
        return;
#ifdef INC_DEBUG
    printf("adding cached '%s' %s\n", filename, get_tok_str(st, ifndef_macro, NULL));
#endif
    e = tcc_malloc(st, sizeof(CachedInclude) + strlen(filename));
    if (!e)
        return;
    e->type = type;
    strcpy(e->filename, filename);
    e->ifndef_macro = ifndef_macro;
    dynarray_add(st, (void ***)&st->cached_includes, &st->nb_cached_includes, e);
    /* add in hash table */
    h = hash_cached_include(st, type, filename);
    e->hash_next = st->cached_includes_hash[h];
    st->cached_includes_hash[h] = st->nb_cached_includes;
}

static void pragma_parse(TCCState *st)
{
    int val;

    next(st);
    if (tok == TOK_pack) {
        /*
          This may be:
          #pragma pack(1) set 
          #pragma pack() reset to default 
          #pragma pack(push,1) push & set 
          #pragma pack(pop) restore previous 
        */
        next(st);
        skip(st, '(');
        if (tok == TOK_ASM_pop) {
            next(st);
            if (st->pack_stack_ptr <= st->pack_stack) {
            stk_error:
               tcc_error(st,"out of pack stack");
            }
            st->pack_stack_ptr--;
        } else {
            val = 0;
            if (tok != ')') {
                if (tok == TOK_ASM_push) {
                    next(st);
                    if (st->pack_stack_ptr >= st->pack_stack + PACK_STACK_SIZE - 1)
                        goto stk_error;
                    st->pack_stack_ptr++;
                    skip(st, ',');
                }
                if (tok != TOK_CINT) {
                pack_error:
                   tcc_error(st, "invalid pack pragma");
                }
                val = tokc.i;
                if (val < 1 || val > 16 || (val & (val - 1)) != 0)
                    goto pack_error;
                next(st);
            }
            *st->pack_stack_ptr = val;
            skip(st, ')');
        }
    }
}

/* is_bof is true if first non space token at beginning of file */
static void preprocess(TCCState * st, int is_bof)
{
    int size, i, c, n, saved_parse_flags;
    char buf[1024], *q, *p;
    char buf1[1024];
    BufferedFile *f;
    Sym *s;
    CachedInclude *e;
    
    saved_parse_flags = parse_flags;
    parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | 
        PARSE_FLAG_LINEFEED;
    next_nomacro(st);
 redo:
    switch(tok) {
    case TOK_DEFINE:
        next_nomacro(st);
        parse_define(st);
        break;
    case TOK_UNDEF:
        next_nomacro(st);
        s = define_find(st, tok);
        /* undefine symbol by putting an invalid name */
        if (s)
            define_undef(s);
        break;
    case TOK_INCLUDE:
    case TOK_INCLUDE_NEXT:
        fch = file->buf_ptr[0];
        /* XXX: incorrect if comments : use next_nomacro with a special mode */
        skip_spaces(st);
        if (fch == '<') {
            c = '>';
            goto read_name;
        } else if (fch == '\"') {
            c = fch;
        read_name:
            /* XXX: better stray handling */
            minp(st);
            q = buf;
            while (fch != c && fch != '\n' && fch != CH_EOF) {
                if ((q - buf) < sizeof(buf) - 1)
                    *q++ = fch;
                minp(st);
            }
            *q = '\0';
            minp(st);
#if 0
            /* eat all spaces and comments after include */
            /* XXX: slightly incorrect */
            while (ch1 != '\n' && ch1 != CH_EOF)
                inp(st);
#endif
        } else {
            /* computed #include : either we have only strings or
               we have anything enclosed in '<>' */
            next(st);
            buf[0] = '\0';
            if (tok == TOK_STR) {
                while (tok != TOK_LINEFEED) {
                    if (tok != TOK_STR) {
                    include_syntax:
                       tcc_error(st,"'#include' expects \"FILENAME\" or <FILENAME>");
                    }
                    pstrcat(st, buf, sizeof(buf), (char *)tokc.cstr->data);
                    next(st);
                }
                c = '\"';
            } else {
                int len;
                while (tok != TOK_LINEFEED) {
                    pstrcat(st, buf, sizeof(buf), get_tok_str(st,tok, &tokc));
                    next(st);
                }
                len = strlen(buf);
                /* check syntax and remove '<>' */
                if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
                    goto include_syntax;
                memmove(buf, buf + 1, len - 2);
                buf[len - 2] = '\0';
                c = '>';
            }
        }

        e = search_cached_include(st, c, buf);
        if (e && define_find(st, e->ifndef_macro)) {
            /* no need to parse the include because the 'ifndef macro'
               is defined */
#ifdef INC_DEBUG
            printf("%s: skipping %s\n", file->filename, buf);
#endif
        } else {
            if (c == '\"') {
                /* first search in current dir if "header.h" */
                size = 0;
                p = strrchr(file->filename, '/');
                if (p) 
                    size = p + 1 - file->filename;
                if (size > sizeof(buf1) - 1)
                    size = sizeof(buf1) - 1;
                memcpy(buf1, file->filename, size);
                buf1[size] = '\0';
                pstrcat(st, buf1, sizeof(buf1), buf);
                f = tcc_open(st, buf1);
                if (f) {
                    if (tok == TOK_INCLUDE_NEXT)
                        tok = TOK_INCLUDE;
                    else
                        goto found;
                }
            }
            if (st->include_stack_ptr >= st->include_stack + INCLUDE_STACK_SIZE)
               tcc_error(st, "#include recursion too deep");
            /* now search in all the include paths */
            n = st->nb_include_paths + st->nb_sysinclude_paths;
            for(i = 0; i < n; i++) {
                const char *path;
                if (i < st->nb_include_paths)
                    path = st->include_paths[i];
                else
                    path = st->sysinclude_paths[i - st->nb_include_paths];
                pstrcpy(st,  buf1, sizeof(buf1), path);
                pstrcat(st, buf1, sizeof(buf1), "/");
                pstrcat(st, buf1, sizeof(buf1), buf);
                f = tcc_open(st, buf1);
                if (f) {
                    if (tok == TOK_INCLUDE_NEXT)
                        tok = TOK_INCLUDE;
                    else
                        goto found;
                }
            }
           tcc_error(st, "include file '%s' not found", buf);
            f = NULL;
        found:
#ifdef INC_DEBUG
            printf("%s: including %s\n", file->filename, buf1);
#endif
            f->inc_type = c;
            pstrcpy(st,  f->inc_filename, sizeof(f->inc_filename), buf);
            /* push current file in stack */
            /* XXX: fix current line init */
            *st->include_stack_ptr++ = file;
            file = f;
            /* add include file debug info */
            if (do_debug) {
                put_stabs(st, file->filename, N_BINCL, 0, 0, 0);
            }
            next_tok_flags |= TOK_FLAG_BOW | TOK_FLAG_BOF | TOK_FLAG_BOL;
            fch = file->buf_ptr[0];
            goto the_end;
        }
        break;
    case TOK_IFNDEF:
        c = 1;
        goto do_ifdef;
    case TOK_IF:
        c = expr_preprocess(st);
        goto do_if;
    case TOK_IFDEF:
        c = 0;
    do_ifdef:
        next_nomacro(st);
        if (tok < TOK_IDENT)
           tcc_error(st,"invalid argument for '#if%sdef'", c ? "n" : "");
        if (is_bof) {
            if (c) {
#ifdef INC_DEBUG
                printf("#ifndef %s\n", get_tok_str(st, tok, NULL));
#endif
                file->ifndef_macro = tok;
            }
        }
        c = (define_find(st, tok) != 0) ^ c;
    do_if:
        if (st->ifdef_stack_ptr >= st->ifdef_stack + IFDEF_STACK_SIZE)
           tcc_error(st, "memory full");
        *st->ifdef_stack_ptr++ = c;
        goto test_skip;
    case TOK_ELSE:
        if (st->ifdef_stack_ptr == st->ifdef_stack)
           tcc_error(st, "#else without matching #if");
        if (st->ifdef_stack_ptr[-1] & 2)
           tcc_error(st, "#else after #else");
        c = (st->ifdef_stack_ptr[-1] ^= 3);
        goto test_skip;
    case TOK_ELIF:
        if (st->ifdef_stack_ptr == st->ifdef_stack)
           tcc_error(st, "#elif without matching #if");
        c = st->ifdef_stack_ptr[-1];
        if (c > 1)
           tcc_error(st, "#elif after #else");
        /* last #if/#elif expression was true: we skip */
        if (c == 1)
            goto skip;
        c = expr_preprocess(st);
        st->ifdef_stack_ptr[-1] = c;
    test_skip:
        if (!(c & 1)) {
        skip:
            preprocess_skip(st);
            is_bof = 0;
            goto redo;
        }
        break;
    case TOK_ENDIF:
        if (st->ifdef_stack_ptr <= file->ifdef_stack_ptr)
           tcc_error(st, "#endif without matching #if");
        st->ifdef_stack_ptr--;
        /* '#ifndef macro' was at the start of file. Now we check if
           an '#endif' is exactly at the end of file */
        if (file->ifndef_macro &&
            st->ifdef_stack_ptr == file->ifdef_stack_ptr) {
            file->ifndef_macro_saved = file->ifndef_macro;
            /* need to set to zero to avoid false matches if another
               #ifndef at middle of file */
            file->ifndef_macro = 0;
            while (tok != TOK_LINEFEED)
                next_nomacro(st);
            next_tok_flags |= TOK_FLAG_ENDIF;
            goto the_end;
        }
        break;
    case TOK_LINE:
        next(st);
        if (tok != TOK_CINT)
           tcc_error(st, "#line");
        file->line_num = tokc.i - 1; /* the line number will be incremented after */
        next(st);
        if (tok != TOK_LINEFEED) {
            if (tok != TOK_STR)
               tcc_error(st, "#line");
            pstrcpy(st,  file->filename, sizeof(file->filename), 
                    (char *)tokc.cstr->data);
        }
        break;
    case TOK_ERROR:
    case TOK_WARNING:
        c = tok;
        fch = file->buf_ptr[0];
        skip_spaces(st);
        q = buf;
        while (fch != '\n' && fch != CH_EOF) {
            if ((q - buf) < sizeof(buf) - 1)
                *q++ = fch;
            minp(st);
        }
        *q = '\0';
        if (c == TOK_ERROR)
           tcc_error(st, "#error %s", buf);
        else
            warning(st, "#warning %s", buf);
        break;
    case TOK_PRAGMA:
        pragma_parse(st);
        break;
    default:
        if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
            /* '!' is ignored to allow C scripts. numbers are ignored
               to emulate cpp behaviour */
        } else {
            if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
               tcc_error(st, "invalid preprocessing directive #%s", get_tok_str(st,tok, &tokc));
        }
        break;
    }
    /* ignore other preprocess commands or #! for C scripts */
    while (tok != TOK_LINEFEED)
        next_nomacro(st);
 the_end:
    parse_flags = saved_parse_flags;
}

/* evaluate escape codes in a string. */
static void parse_escape_string(TCCState *st, CString *outstr, const uint8_t *buf, int is_long)
{
    int c, n;
    const uint8_t *p;

    p = buf;
    for(;;) {
        c = *p;
        if (c == '\0')
            break;
        if (c == '\\') {
            p++;
            /* escape */
            c = *p;
            switch(c) {
            case '0': case '1': case '2': case '3':
            case '4': case '5': case '6': case '7':
                /* at most three octal digits */
                n = c - '0';
                p++;
                c = *p;
                if (isoct(st, c)) {
                    n = n * 8 + c - '0';
                    p++;
                    c = *p;
                    if (isoct(st, c)) {
                        n = n * 8 + c - '0';
                        p++;
                    }
                }
                c = n;
                goto add_char_nonext;
            case 'x':
            case 'u':
            case 'U':
                p++;
                n = 0;
                for(;;) {
                    c = *p;
                    if (c >= 'a' && c <= 'f')
                        c = c - 'a' + 10;
                    else if (c >= 'A' && c <= 'F')
                        c = c - 'A' + 10;
                    else if (isnum(st, c))
                        c = c - '0';
                    else
                        break;
                    n = n * 16 + c;
                    p++;
                }
                c = n;
                goto add_char_nonext;
            case 'a':
                c = '\a';
                break;
            case 'b':
                c = '\b';
                break;
            case 'f':
                c = '\f';
                break;
            case 'n':
                c = '\n';
                break;
            case 'r':
                c = '\r';
                break;
            case 't':
                c = '\t';
                break;
            case 'v':
                c = '\v';
                break;
            case 'e':
                if (!gnu_ext)
                    goto invalid_escape;
                c = 27;
                break;
            case '\'':
            case '\"':
            case '\\': 
            case '?':
                break;
            default:
            invalid_escape:
                if (c >= '!' && c <= '~')
                    warning(st, "unknown escape sequence: \'\\%c\'", c);
                else
                    warning(st, "unknown escape sequence: \'\\x%x\'", c);
                break;
            }
        }
        p++;
    add_char_nonext:
        if (!is_long)
            cstr_ccat(st, outstr, c);
        else
            cstr_wccat(st, outstr, c);
    }
    /* add a trailing '\0' */
    if (!is_long)
        cstr_ccat(st, outstr, '\0');
    else
        cstr_wccat(st, outstr, '\0');
}

/* we use 64 bit numbers */
#define BN_SIZE 2

/* bn = (bn << shift) | or_val */
void bn_lshift(unsigned int *bn, int shift, int or_val)
{
    int i;
    unsigned int v;
    for(i=0;i<BN_SIZE;i++) {
        v = bn[i];
        bn[i] = (v << shift) | or_val;
        or_val = v >> (32 - shift);
    }
}

void bn_zero(unsigned int *bn)
{
    int i;
    for(i=0;i<BN_SIZE;i++) {
        bn[i] = 0;
    }
}

/* parse number in null terminated string 'p' and return it in the
   current token */
void parse_number(TCCState *st, const char *p)
{
    int b, t, shift, frac_bits, s, exp_val, ch;
    char *q;
    unsigned int bn[BN_SIZE];
    double d;

    /* number */
    q = token_buf;
    ch = *p++;
    t = ch;
    ch = *p++;
    *q++ = t;
    b = 10;
    if (t == '.') {
        goto float_frac_parse;
    } else if (t == '0') {
        if (ch == 'x' || ch == 'X') {
            q--;
            ch = *p++;
            b = 16;
        } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
            q--;
            ch = *p++;
            b = 2;
        }
    }
    /* parse all digits. cannot check octal numbers at this stage
       because of floating point constants */
    while (1) {
        if (ch >= 'a' && ch <= 'f')
            t = ch - 'a' + 10;
        else if (ch >= 'A' && ch <= 'F')
            t = ch - 'A' + 10;
        else if (isnum(st, ch))
            t = ch - '0';
        else
            break;
        if (t >= b)
            break;
        if (q >= token_buf + STRING_MAX_SIZE) {
        num_too_long:
           tcc_error(st, "number too long");
        }
        *q++ = ch;
        ch = *p++;
    }
    if (ch == '.' ||
        ((ch == 'e' || ch == 'E') && b == 10) ||
        ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
        if (b != 10) {
            /* NOTE: strtox should support that for hexa numbers, but
               non ISOC99 libcs do not support it, so we prefer to do
               it by hand */
            /* hexadecimal or binary floats */
            /* XXX: handle overflows */
            *q = '\0';
            if (b == 16)
                shift = 4;
            else 
                shift = 2;
            bn_zero(bn);
            q = token_buf;
            while (1) {
                t = *q++;
                if (t == '\0') {
                    break;
                } else if (t >= 'a') {
                    t = t - 'a' + 10;
                } else if (t >= 'A') {
                    t = t - 'A' + 10;
                } else {
                    t = t - '0';
                }
                bn_lshift(bn, shift, t);
            }
            frac_bits = 0;
            if (ch == '.') {
                ch = *p++;
                while (1) {
                    t = ch;
                    if (t >= 'a' && t <= 'f') {
                        t = t - 'a' + 10;
                    } else if (t >= 'A' && t <= 'F') {
                        t = t - 'A' + 10;
                    } else if (t >= '0' && t <= '9') {
                        t = t - '0';
                    } else {
                        break;
                    }
                    if (t >= b)
                       tcc_error(st, "invalid digit");
                    bn_lshift(bn, shift, t);
                    frac_bits += shift;
                    ch = *p++;
                }
            }
            if (ch != 'p' && ch != 'P')
                expect(st, "exponent");
            ch = *p++;
            s = 1;
            exp_val = 0;
            if (ch == '+') {
                ch = *p++;
            } else if (ch == '-') {
                s = -1;
                ch = *p++;
            }
            if (ch < '0' || ch > '9')
                expect(st, "exponent digits");
            while (ch >= '0' && ch <= '9') {
                exp_val = exp_val * 10 + ch - '0';
                ch = *p++;
            }
            exp_val = exp_val * s;
            
            /* now we can generate the number */
            /* XXX: should patch directly float number */
            d = (double)bn[1] * 4294967296.0 + (double)bn[0];
            d = ldexp(d, exp_val - frac_bits);
            t = toup(st, ch);
            if (t == 'F') {
                ch = *p++;
                tok = TOK_CFLOAT;
                /* float : should handle overflow */
                tokc.f = (float)d;
            } else if (t == 'L') {
                ch = *p++;
                tok = TOK_CLDOUBLE;
                /* XXX: not large enough */
                tokc.ld = (long double)d;
            } else {
                tok = TOK_CDOUBLE;
                tokc.d = d;
            }
        } else {
            /* decimal floats */
            if (ch == '.') {
                if (q >= token_buf + STRING_MAX_SIZE)
                    goto num_too_long;
                *q++ = ch;
                ch = *p++;
            float_frac_parse:
                while (ch >= '0' && ch <= '9') {
                    if (q >= token_buf + STRING_MAX_SIZE)
                        goto num_too_long;
                    *q++ = ch;
                    ch = *p++;
                }
            }
            if (ch == 'e' || ch == 'E') {
                if (q >= token_buf + STRING_MAX_SIZE)
                    goto num_too_long;
                *q++ = ch;
                ch = *p++;
                if (ch == '-' || ch == '+') {
                    if (q >= token_buf + STRING_MAX_SIZE)
                        goto num_too_long;
                    *q++ = ch;
                    ch = *p++;
                }
                if (ch < '0' || ch > '9')
                    expect(st, "exponent digits");
                while (ch >= '0' && ch <= '9') {
                    if (q >= token_buf + STRING_MAX_SIZE)
                        goto num_too_long;
                    *q++ = ch;
                    ch = *p++;
                }
            }
            *q = '\0';
            t = toup(st, ch);
            errno = 0;
            if (t == 'F') {
                ch = *p++;
                tok = TOK_CFLOAT;
                tokc.f = strtof(token_buf, NULL);
            } else if (t == 'L') {
                ch = *p++;
                tok = TOK_CLDOUBLE;
                tokc.ld = strtold(token_buf, NULL);
            } else {
                tok = TOK_CDOUBLE;
                tokc.d = strtod(token_buf, NULL);
            }
        }
    } else {
        unsigned long long n, n1;
        int lcount, ucount;

        /* integer number */
        *q = '\0';
        q = token_buf;
        if (b == 10 && *q == '0') {
            b = 8;
            q++;
        }
        n = 0;
        while(1) {
            t = *q++;
            /* no need for checks except for base 10 / 8 errors */
            if (t == '\0') {
                break;
            } else if (t >= 'a') {
                t = t - 'a' + 10;
            } else if (t >= 'A') {
                t = t - 'A' + 10;
            } else {
                t = t - '0';
                if (t >= b)
                   tcc_error(st, "invalid digit");
            }
            n1 = n;
            n = n * b + t;
            /* detect overflow */
            /* XXX: this test is not reliable */
            if (n < n1)
               tcc_error(st, "integer constant overflow");
        }
        
        /* XXX: not exactly ANSI compliant */
        if ((n & 0xffffffff00000000LL) != 0) {
            if ((n >> 63) != 0)
                tok = TOK_CULLONG;
            else
                tok = TOK_CLLONG;
        } else if (n > 0x7fffffff) {
            tok = TOK_CUINT;
        } else {
            tok = TOK_CINT;
        }
        lcount = 0;
        ucount = 0;
        for(;;) {
            t = toup(st, ch);
            if (t == 'L') {
                if (lcount >= 2)
                   tcc_error(st, "three 'l's in integer constant");
                lcount++;
                if (lcount == 2) {
                    if (tok == TOK_CINT)
                        tok = TOK_CLLONG;
                    else if (tok == TOK_CUINT)
                        tok = TOK_CULLONG;
                }
                ch = *p++;
            } else if (t == 'U') {
                if (ucount >= 1)
                   tcc_error(st, "two 'u's in integer constant");
                ucount++;
                if (tok == TOK_CINT)
                    tok = TOK_CUINT;
                else if (tok == TOK_CLLONG)
                    tok = TOK_CULLONG;
                ch = *p++;
            } else {
                break;
            }
        }
        if (tok == TOK_CINT || tok == TOK_CUINT)
            tokc.ui = n;
        else
            tokc.ull = n;
    }
}


#define PARSE2(st, c1, tok1, c2, tok2)              \
    case c1:                                    \
        PEEKC(st, c, p);                            \
        if (c == c2) {                          \
            p++;                                \
            tok = tok2;                         \
        } else {                                \
            tok = tok1;                         \
        }                                       \
        break;

/* return next token without macro substitution */
static inline void next_nomacro1(TCCState *st)
{
    int t, c, is_long;
    TokenSym *ts;
    uint8_t *p, *p1;
    unsigned int h;

    p = file->buf_ptr;
 redo_no_start:
    c = *p;
    switch(c) {
    case ' ':
    case '\t':
    case '\f':
    case '\v':
    case '\r':
        p++;
        next_tok_flags |= TOK_FLAG_BOW;
        goto redo_no_start;
        
    case '\\':
        /* first look if it is in fact an end of buffer */
        if (p >= file->buf_end) {
            file->buf_ptr = p;
            handle_eob(st);
            p = file->buf_ptr;
            if (p >= file->buf_end)
                goto parse_eof;
            else
                goto redo_no_start;
        } else {
            file->buf_ptr = p;
            fch = *p;
            handle_stray(st);
            p = file->buf_ptr;
            goto redo_no_start;
        }
    parse_eof:
        {
            if (parse_flags & PARSE_FLAG_LINEFEED) {
                tok = TOK_LINEFEED;
            } else if (st->include_stack_ptr == st->include_stack ||
                       !(parse_flags & PARSE_FLAG_PREPROCESS)) {
                /* no include left : end of file. */
                tok = TOK_EOF;
            } else {
                /* pop include file */
                
                /* test if previous '#endif' was after a #ifdef at
                   start of file */
                if (next_tok_flags & TOK_FLAG_ENDIF) {
#ifdef INC_DEBUG
                    printf("#endif %s\n", get_tok_str(st, file->ifndef_macro_saved, NULL));
#endif
                    add_cached_include(st, file->inc_type, file->inc_filename,
                                       file->ifndef_macro_saved);
                }

                /* add end of include file debug info */
                if (do_debug) {
                    put_stabd(st, N_EINCL, 0, 0);
                }
                /* pop include stack */
                tcc_close(file);
                st->include_stack_ptr--;
                file = *st->include_stack_ptr;
                p = file->buf_ptr;
                goto redo_no_start;
            }
        }
        break;

    case '\n':
        if (parse_flags & PARSE_FLAG_LINEFEED) {
            tok = TOK_LINEFEED;
        } else {
            file->line_num++;
            next_tok_flags |= TOK_FLAG_BOW | TOK_FLAG_BOL;
            p++;
            goto redo_no_start;
        }
        break;

    case '#':
        /* XXX: simplify */
        PEEKC(st, c, p);
        if ((next_tok_flags & TOK_FLAG_BOL) && 
            (parse_flags & PARSE_FLAG_PREPROCESS)) {
            file->buf_ptr = p;
            preprocess(st, next_tok_flags & TOK_FLAG_BOF);
            p = file->buf_ptr;
            goto redo_no_start;
        } else {
            if (c == '#') {
                p++;
                tok = TOK_TWOSHARPS;
            } else {
                if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
                    p = parse_line_comment(st, p - 1);
                    goto redo_no_start;
                } else {
                    tok = '#';
                }
            }
        }
        break;

    case 'a': case 'b': case 'c': case 'd':
    case 'e': case 'f': case 'g': case 'h':
    case 'i': case 'j': case 'k': case 'l':
    case 'm': case 'n': case 'o': case 'p':
    case 'q': case 'r': case 's': case 't':
    case 'u': case 'v': case 'w': case 'x':
    case 'y': case 'z': 
    case 'A': case 'B': case 'C': case 'D':
    case 'E': case 'F': case 'G': case 'H':
    case 'I': case 'J': case 'K': 
    case 'M': case 'N': case 'O': case 'P':
    case 'Q': case 'R': case 'S': case 'T':
    case 'U': case 'V': case 'W': case 'X':
    case 'Y': case 'Z': 
    case '_':
    parse_ident_fast:
        p1 = p;
        h = TOK_HASH_INIT;
        h = TOK_HASH_FUNC(h, c);
        p++;
        for(;;) {
            c = *p;
            if (!isidnum_table[c])
                break;
            h = TOK_HASH_FUNC(h, c);
            p++;
        }
        if (c != '\\') {
            TokenSym **pts;
            int len;

            /* fast case : no stray found, so we have the full token
               and we have already hashed it */
            len = p - p1;
            h &= (TOK_HASH_SIZE - 1);
            pts = &hash_ident[h];
            for(;;) {
                ts = *pts;
                if (!ts)
                    break;
                if (ts->len == len && !memcmp(ts->str, p1, len))
                    goto token_found;
                pts = &(ts->hash_next);
            }
            ts = tok_alloc_new(st, pts, p1, len);
        token_found: ;
        } else {
            /* slower case */
            cstr_reset(st, &tokcstr);

            while (p1 < p) {
                cstr_ccat(st, &tokcstr, *p1);
                p1++;
            }
            p--;
            PEEKC(st, c, p);
        parse_ident_slow:
            while (isidnum_table[c]) {
                cstr_ccat(st, &tokcstr, c);
                PEEKC(st, c, p);
            }
            ts = tok_alloc(st, tokcstr.data, tokcstr.size);
        }
        tok = ts->tok;
        break;
    case 'L':
        t = p[1];
        if (t != '\\' && t != '\'' && t != '\"') {
            /* fast case */
            goto parse_ident_fast;
        } else {
            PEEKC(st, c, p);
            if (c == '\'' || c == '\"') {
                is_long = 1;
                goto str_const;
            } else {
                cstr_reset(st, &tokcstr);
                cstr_ccat(st, &tokcstr, 'L');
                goto parse_ident_slow;
            }
        }
        break;
    case '0': case '1': case '2': case '3':
    case '4': case '5': case '6': case '7':
    case '8': case '9':

        cstr_reset(st, &tokcstr);
        /* after the first digit, accept digits, alpha, '.' or sign if
           prefixed by 'eEpP' */
    parse_num:
        for(;;) {
            t = c;
            cstr_ccat(st, &tokcstr, c);
            PEEKC(st, c, p);
            if (!(isnum(st, c) || isid(st, c) || c == '.' ||
                  ((c == '+' || c == '-') && 
                   (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
                break;
        }
        /* We add a trailing '\0' to ease parsing */
        cstr_ccat(st, &tokcstr, '\0');
        tokc.cstr = &tokcstr;
        tok = TOK_PPNUM;
        break;
    case '.':
        /* special dot handling because it can also start a number */
        PEEKC(st, c, p);
        if (isnum(st, c)) {
            cstr_reset(st, &tokcstr);
            cstr_ccat(st, &tokcstr, '.');
            goto parse_num;
        } else if (c == '.') {
            PEEKC(st, c, p);
            if (c != '.')
                expect(st, "'.'");
            PEEKC(st, c, p);
            tok = TOK_DOTS;
        } else {
            tok = '.';
        }
        break;
    case '\'':
    case '\"':
        is_long = 0;
    str_const:
        {
            CString str;
            int sep;

            sep = c;

            /* parse the string */
            cstr_new(st, &str);
            p = parse_pp_string(st, p, sep, &str);
            cstr_ccat(st, &str, '\0');
            
            /* eval the escape (should be done as TOK_PPNUM) */
            cstr_reset(st, &tokcstr);
            parse_escape_string(st, &tokcstr, str.data, is_long);
            cstr_free(st, &str);

            if (sep == '\'') {
                int char_size;
                /* XXX: make it portable */
                if (!is_long)
                    char_size = 1;
                else
                    char_size = sizeof(nwchar_t);
                if (tokcstr.size <= char_size)
                   tcc_error(st, "empty character constant");
                if (tokcstr.size > 2 * char_size)
                    warning(st, "multi-character character constant");
                if (!is_long) {
                    tokc.i = *(int8_t *)tokcstr.data;
                    tok = TOK_CCHAR;
                } else {
                    tokc.i = *(nwchar_t *)tokcstr.data;
                    tok = TOK_LCHAR;
                }
            } else {
                tokc.cstr = &tokcstr;
                if (!is_long)
                    tok = TOK_STR;
                else
                    tok = TOK_LSTR;
            }
        }
        break;

    case '<':
        PEEKC(st, c, p);
        if (c == '=') {
            p++;
            tok = TOK_LE;
        } else if (c == '<') {
            PEEKC(st, c, p);
            if (c == '=') {
                p++;
                tok = TOK_A_SHL;
            } else {
                tok = TOK_SHL;
            }
        } else {
            tok = TOK_LT;
        }
        break;
        
    case '>':
        PEEKC(st, c, p);
        if (c == '=') {
            p++;
            tok = TOK_GE;
        } else if (c == '>') {
            PEEKC(st, c, p);
            if (c == '=') {
                p++;
                tok = TOK_A_SAR;
            } else {
                tok = TOK_SAR;
            }
        } else {
            tok = TOK_GT;
        }
        break;
        
    case '&':
        PEEKC(st, c, p);
        if (c == '&') {
            p++;
            tok = TOK_LAND;
        } else if (c == '=') {
            p++;
            tok = TOK_A_AND;
        } else {
            tok = '&';
        }
        break;
        
    case '|':
        PEEKC(st, c, p);
        if (c == '|') {
            p++;
            tok = TOK_LOR;
        } else if (c == '=') {
            p++;
            tok = TOK_A_OR;
        } else {
            tok = '|';
        }
        break;

    case '+':
        PEEKC(st, c, p);
        if (c == '+') {
            p++;
            tok = TOK_INC;
        } else if (c == '=') {
            p++;
            tok = TOK_A_ADD;
        } else {
            tok = '+';
        }
        break;
        
    case '-':
        PEEKC(st, c, p);
        if (c == '-') {
            p++;
            tok = TOK_DEC;
        } else if (c == '=') {
            p++;
            tok = TOK_A_SUB;
        } else if (c == '>') {
            p++;
            tok = TOK_ARROW;
        } else {
            tok = '-';
        }
        break;

    PARSE2(st, '!', '!', '=', TOK_NE)
    PARSE2(st, '=', '=', '=', TOK_EQ)
    PARSE2(st, '*', '*', '=', TOK_A_MUL)
    PARSE2(st, '%', '%', '=', TOK_A_MOD)
    PARSE2(st, '^', '^', '=', TOK_A_XOR)
        
        /* comments or operator */
    case '/':
        PEEKC(st, c, p);
        if (c == '*') {
            p = parse_comment(st, p);
            next_tok_flags |= TOK_FLAG_BOW;
            goto redo_no_start;
        } else if (c == '/') {
            p = parse_line_comment(st, p);
            next_tok_flags |= TOK_FLAG_BOW;
            goto redo_no_start;
        } else if (c == '=') {
            p++;
            tok = TOK_A_DIV;
        } else {
            tok = '/';
        }
        break;
        
        /* simple tokens */
    case '(':
    case ')':
    case '[':
    case ']':
    case '{':
    case '}':
    case ',':
    case ';':
    case ':':
    case '?':
    case '~':
    case '$': /* only used in assembler */
    case '@': /* dito */
        tok = c;
        p++;
        break;
    default:
       tcc_error(st, "unrecognized character \\x%02x", c);
        break;
    }
    file->buf_ptr = p;
    tok_flags = next_tok_flags;
    next_tok_flags = 0;
#if defined(PARSE_DEBUG)
    printf("token = %s\n", get_tok_str(st, tok, &tokc));
#endif
}

/* return next token without macro substitution. Can read input from
   macro_ptr buffer */
static void next_nomacro(TCCState *st)
{
    if (macro_ptr) {
    redo:
        tok = *macro_ptr;
        if (tok) {
            TOK_GET(tok, tok_flags, macro_ptr, tokc);
            if (tok == TOK_LINENUM) {
                file->line_num = tokc.i;
                goto redo;
            }
        }
    } else {
        next_nomacro1(st );
    }
}

/* substitute args in macro_str and return allocated string */
static int *macro_arg_subst(TCCState *state, Sym **nested_list, int *macro_str, Sym *args)
{
    int *st, last_tok, t, tf, save_tf, notfirst;
    Sym *s;
    CValue cval;
    TokenString str;
    CString cstr;

    tok_str_new(state, &str);
    last_tok = 0;
    while(1) {
        TOK_GET(t, tf, macro_str, cval);
        save_tf = tf;
        if (!t)
            break;
        if (t == '#') {
            /* stringize */
            TOK_GET(t, tf, macro_str, cval);
            if (!t)
                break;
            s = sym_find2(state, args, t);
            if (s) {
                cstr_new(state, &cstr);
                st = (int *)s->c;
                notfirst = 0;
                while (*st) {
                    TOK_GET(t, tf, st, cval);
                    if (notfirst && tf & TOK_FLAG_BOW)
                        cstr_ccat(state, &cstr, ' ');
                    cstr_cat(state, &cstr, get_tok_str(state, t, &cval));
                    notfirst = 1;
                }
                cstr_ccat(state, &cstr, '\0');
#ifdef PP_DEBUG
                printf("stringize: %s\n", (char *)cstr.data);
#endif
                /* add string */
                cval.cstr = &cstr;
                tok_str_add2(state, &str, TOK_STR, save_tf, &cval);
                cstr_free(state, &cstr);
            } else {
                tok_str_add2(state, &str, t, save_tf, &cval);
            }
        } else if (t >= TOK_IDENT) {
            s = sym_find2(state, args, t);
            if (s) {
                st = (int *)s->c;
                st[1] = save_tf;
                /* if '##' is present before or after, no arg substitution */
                if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
                    /* special case for var arg macros : ## eats the
                       ',' if empty VA_ARGS variable. */
                    /* XXX: test of the ',' is not 100%
                       reliable. should fix it to avoid security
                       problems */
                    if (gnu_ext && s->type.t &&
                        last_tok == TOK_TWOSHARPS && 
                        str.len >= 4 && str.str[str.len - 4] == ',') {
                        if (*st == 0) {
                            /* suppress ',' '##' */
                            str.len -= 4;
                            next_tok_flags = tok_flags;
                        } else {
                            /* suppress '##' and add variable */
                            str.len -= 2;
                            goto add_var;
                        }
                    } else {
                        int t1;
                    add_var:
                        for(;;) {
                            TOK_GET(t1, tf, st, cval);
                            if (!t1)
                                break;
                            tok_str_add2(state, &str, t1, save_tf, &cval);
                        }
                    }
                } else {
                    /* NOTE: the stream cannot be read when macro
                       substituing an argument */
                    macro_subst(state, &str, nested_list, st, NULL);
                }
            } else {
                tok_str_add(state, &str, t, tf);
            }
        } else {
            tok_str_add2(state, &str, t, tf, &cval);
        }
        last_tok = t;
    }
    tok_str_add(state, &str, 0, 0);
    return str.str;
}

static char const ab_month_name[12][4] =
{
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

/* do macro substitution of current token with macro 's' and add
   result to (tok_str,tok_len). 'nested_list' is the list of all
   macros we got inside to avoid recursing. Return non zero if no
   substitution needs to be done */
static int macro_subst_tok(TCCState *st, TokenString *tok_str,
                           Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
{
    Sym *args, *sa, *sa1;
    int mstr_allocated, parlevel, *mstr, t, t1;
    TokenString str;
    char *cstrval;
    CValue cval;
    CString cstr;
    char buf[32];
    
    /* if symbol is a macro, prepare substitution */
    /* special macros */
    if (tok == TOK___LINE__) {
        snprintf(buf, sizeof(buf), "%d", file->line_num);
        cstrval = buf;
        t1 = TOK_PPNUM;
        goto add_cstr1;
    } else if (tok == TOK___FILE__) {
        cstrval = file->filename;
        goto add_cstr;
    } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
        time_t ti;
        struct tm *tm;

        time(&ti);
        tm = localtime(&ti);
        if (tok == TOK___DATE__) {
            snprintf(buf, sizeof(buf), "%s %2d %d", 
                     ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
        } else {
            snprintf(buf, sizeof(buf), "%02d:%02d:%02d", 
                     tm->tm_hour, tm->tm_min, tm->tm_sec);
        }
        cstrval = buf;
    add_cstr:
        t1 = TOK_STR;
    add_cstr1:
        cstr_new(st, &cstr);
        cstr_cat(st, &cstr, cstrval);
        cstr_ccat(st, &cstr, '\0');
        cval.cstr = &cstr;
        tok_str_add2(st, tok_str, t1, tok_flags, &cval);
        cstr_free(st, &cstr);
    } else {
        mstr = (int *)s->c;
        mstr[1] = tok_flags;
        mstr_allocated = 0;
        if (s->type.t == MACRO_FUNC) {
            /* NOTE: we do not use next_nomacro to avoid eating the
               next token. XXX: find better solution */
        redo:
            if (macro_ptr) {
                t = *macro_ptr;
                if (t == 0 && can_read_stream) {
                    /* end of macro stream: we must look at the token
                       after in the file */
                    struct macro_level *ml = *can_read_stream;
                    macro_ptr = NULL;
                    if (ml)
                    {
                        macro_ptr = ml->p;
                        ml->p = NULL;
                        *can_read_stream = ml -> prev;
                    }
                    goto redo;
                }
            } else {
                /* XXX: incorrect with comments */
                fch = file->buf_ptr[0];
                while (is_space(st, fch) || fch == '\n')
                    cinp(st);
                t = fch;
            }
            if (t != '(') /* no macro subst */
                return -1;
                    
            /* argument macro */
            next_nomacro(st);
            next_nomacro(st);
            args = NULL;
            sa = s->next;
            /* NOTE: empty args are allowed, except if no args */
            for(;;) {
                /* handle '()' case */
                if (!args && !sa && tok == ')')
                    break;
                if (!sa)
                   tcc_error(st, "macro '%s' used with too many args",
                          get_tok_str(st, s->v, 0));
                tok_str_new(st, &str);
                parlevel = 0;
                /* NOTE: non zero sa->t indicates VA_ARGS */
                while ((parlevel > 0 || 
                        (tok != ')' && 
                         (tok != ',' || sa->type.t))) && 
                       tok != -1) {
                    if (tok == '(')
                        parlevel++;
                    else if (tok == ')')
                        parlevel--;
                    tok_str_add2(st, &str, tok, tok_flags, &tokc);
                    next_nomacro(st);
                }
                tok_str_add(st, &str, 0, 0);
                sym_push2(st, &args, sa->v & ~SYM_FIELD, sa->type.t, (int)str.str);
                sa = sa->next;
                if (tok == ')') {
                    /* special case for gcc var args: add an empty
                       var arg argument if it is omitted */
                    if (sa && sa->type.t && gnu_ext)
                        continue;
                    else
                        break;
                }
                if (tok != ',')
                    expect(st, ",");
                next_nomacro(st);
            }
            if (sa) {
               tcc_error(st, "macro '%s' used with too few args",
                      get_tok_str(st, s->v, 0));
            }

            /* now subst each arg */
            mstr = macro_arg_subst(st, nested_list, mstr, args);
            /* free memory */
            sa = args;
            while (sa) {
                sa1 = sa->prev;
                tok_str_free(st, (int *)sa->c);
                sym_free(st, sa);
                sa = sa1;
            }
            mstr_allocated = 1;
        }
        sym_push2(st, nested_list, s->v, 0, 0);
        macro_subst(st, tok_str, nested_list, mstr, can_read_stream);
        /* pop nested defined symbol */
        sa1 = *nested_list;
        *nested_list = sa1->prev;
        sym_free(st, sa1);
        if (mstr_allocated)
            tok_str_free(st, mstr);
    }
    return 0;
}

/* handle the '##' operator. Return NULL if no '##' seen. Otherwise
   return the resulting string (which must be freed). */
static inline int *macro_twosharps(TCCState *st, const int *macro_str)
{
    TokenSym *ts;
    const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
    int t, tf;
    const char *p1, *p2;
    CValue cval;
    TokenString macro_str1;
    CString cstr;

    start_macro_ptr = macro_str;
    /* we search the first '##' */
    for(;;) {
        macro_ptr1 = macro_str;
        TOK_GET(t, tf, macro_str, cval);
        /* nothing more to do if end of string */
        if (t == 0)
            return NULL;
        if (*macro_str == TOK_TWOSHARPS)
            break;
    }

    /* we saw '##', so we need more processing to handle it */
    cstr_new(st, &cstr);
    tok_str_new(st, &macro_str1);
    tok = t;
    tok_flags = tf;
    tokc = cval;

    /* add all tokens seen so far */
    for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
        TOK_GET(t, tf, ptr, cval);
        tok_str_add2(st, &macro_str1, t, tf, &cval);
    }
    saved_macro_ptr = macro_ptr;
    /* XXX: get rid of the use of macro_ptr here */
    macro_ptr = (int *)macro_str;
    for(;;) {
        while (*macro_ptr == TOK_TWOSHARPS) {
            macro_ptr+=2;
            macro_ptr1 = macro_ptr;
            t = *macro_ptr;
            if (t) {
                TOK_GET(t, tf, macro_ptr, cval);
                /* We concatenate the two tokens if we have an
                   identifier or a preprocessing number */
                cstr_reset(st, &cstr);
                p1 = get_tok_str(st, tok, &tokc);
                cstr_cat(st, &cstr, p1);
                p2 = get_tok_str(st, t, &cval);
                cstr_cat(st, &cstr, p2);
                cstr_ccat(st, &cstr, '\0');
                
                if ((tok >= TOK_IDENT || tok == TOK_PPNUM) && 
                    (t >= TOK_IDENT || t == TOK_PPNUM)) {
                    if (tok == TOK_PPNUM) {
                        /* if number, then create a number token */
                        /* NOTE: we cannot use cstr directly for this
                           because if there are multiple token pastings
                           in a sequence the concatenation will reset
                           cstr before the final token is ready. */
                        cstr_reset(st, &tokcstr);
                        cstr_cat(st, &tokcstr, cstr.data);
                        cstr_ccat(st, &tokcstr, '\0');
                        tokc.cstr = &tokcstr;
                    } else {
                        /* if identifier, we must do a test to
                           validate we have a correct identifier */
                        if (t == TOK_PPNUM) {
                            const char *p;
                            int c;

                            p = p2;
                            for(;;) {
                                c = *p;
                                if (c == '\0')
                                    break;
                                p++;
                                if (!isnum(st, c) && !isid(st, c))
                                    goto error_pasting;
                            }
                        }
                        ts = tok_alloc(st, cstr.data, strlen(cstr.data));
                        tok = ts->tok; /* modify current token */
                    }
                } else {
                    const char *str = cstr.data;
                    const unsigned char *q;

                    /* we look for a valid token */
                    /* XXX: do more extensive checks */
                    if (!strcmp(str, ">>=")) {
                        tok = TOK_A_SAR;
                    } else if (!strcmp(str, "<<=")) {
                        tok = TOK_A_SHL;
                    } else if (strlen(str) == 2) {
                        /* search in two bytes table */
                        q = tok_two_chars;
                        for(;;) {
                            if (!*q)
                                goto error_pasting;
                            if (q[0] == str[0] && q[1] == str[1])
                                break;
                            q += 3;
                        }
                        tok = q[2];
                    } else {
                    error_pasting:
                        /* NOTE: because get_tok_str use a static buffer,
                           we must save it */
                        cstr_reset(st, &cstr);
                        p1 = get_tok_str(st, tok, &tokc);
                        cstr_cat(st, &cstr, p1);
                        cstr_ccat(st, &cstr, '\0');
                        p2 = get_tok_str(st, t, &cval);
                        warning(st, "pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
                        /* cannot merge tokens: just add them separately */
                        tok_str_add2(st, &macro_str1, tok, tok_flags, &tokc);
                        /* XXX: free associated memory ? */
                        tok = t;
                        tokc = cval;
                    }
                }
            }
        }
        tok_str_add2(st, &macro_str1, tok, tok_flags, &tokc);
        next_nomacro(st);
        if (tok == 0)
            break;
    }
    macro_ptr = (int *)saved_macro_ptr;
    cstr_free(st, &cstr);
    tok_str_add(st, &macro_str1, 0, 0);
    return macro_str1.str;
}


/* do macro substitution of macro_str and add result to
   (tok_str,tok_len). 'nested_list' is the list of all macros we got
   inside to avoid recursing. */
static void macro_subst(TCCState *st, TokenString *tok_str, Sym **nested_list, 
                        const int *macro_str, struct macro_level ** can_read_stream)
{
    Sym *s;
    int *macro_str1;
    const int *ptr;
    int t, tf, ret;
    CValue cval;
    struct macro_level ml;
    
    /* first scan for '##' operator handling */
    ptr = macro_str;
    macro_str1 = macro_twosharps(st, ptr);
    if (macro_str1) 
        ptr = macro_str1;
    while (1) {
        /* NOTE: ptr == NULL can only happen if tokens are read from
           file stream due to a macro function call */
        if (ptr == NULL)
            break;
        TOK_GET(t, tf, ptr, cval);
        if (t == 0)
            break;
        s = define_find(st, t);
        if (s != NULL) {
            /* if nested substitution, do nothing */
            if (sym_find2(st, *nested_list, t))
                goto no_subst;
            ml.p = macro_ptr;
            if (can_read_stream)
                ml.prev = *can_read_stream, *can_read_stream = &ml;
            macro_ptr = (int *)ptr;
            tok = t;
            tok_flags = tf;
            ret = macro_subst_tok(st, tok_str, nested_list, s, can_read_stream);
            ptr = (int *)macro_ptr;
            macro_ptr = ml.p;
            if (can_read_stream && *can_read_stream == &ml)
                    *can_read_stream = ml.prev;
            if (ret != 0)
                goto no_subst;
        } else {
        no_subst:
            tok_str_add2(st, tok_str, t, tf, &cval);
        }
    }
    if (macro_str1)
        tok_str_free(st, macro_str1);
}


/* return next token with macro substitution */
static void next(TCCState *st)
{
    Sym *nested_list, *s;
    TokenString str;
    struct macro_level *ml;

 redo:
    next_nomacro(st);
    if (!macro_ptr) {
        /* if not reading from macro substituted string, then try
           to substitute macros */
        if (tok >= TOK_IDENT &&
            (parse_flags & PARSE_FLAG_PREPROCESS)) {
            s = define_find(st, tok);
            if (s) {
                /* we have a macro: we try to substitute */
                tok_str_new(st, &str);
                nested_list = NULL;
                ml = NULL;
                if (macro_subst_tok(st, &str, &nested_list, s, &ml) == 0) {
                    /* substitution done, NOTE: maybe empty */
                    tok_str_add(st, &str, 0, 0);
                    macro_ptr = str.str;
                    macro_ptr_allocated = str.str;
                    goto redo;
                }
            }
        }
    } else {
        if (tok == 0) {
            /* end of macro or end of unget buffer */
            if (unget_buffer_enabled) {
                macro_ptr = unget_saved_macro_ptr;
                unget_buffer_enabled = 0;
            } else {
                /* end of macro string: free it */
                tok_str_free(st, macro_ptr_allocated);
                macro_ptr = NULL;
            }
            goto redo;
        }
    }
    
    /* convert preprocessor tokens into C tokens */
    if (tok == TOK_PPNUM &&
        (parse_flags & PARSE_FLAG_TOK_NUM)) {
        parse_number(st, (char *)tokc.cstr->data);
    }
    
}

/* push back current token and set current token to 'last_tok'. Only
   identifier case handled for labels. */
static inline void unget_tok(TCCState *st, int last_tok)
{
    int i, n;
    int *q;
    unget_saved_macro_ptr = macro_ptr;
    unget_buffer_enabled = 1;
    q = unget_saved_buffer;
    macro_ptr = q;
    *q++ = tok;
    n = tok_ext_size(st, tok) - 1;
    for(i=0;i<n;i++)
        *q++ = tokc.tab[i];
    *q = 0; /* end of token string */
    tok = last_tok;
}


void swap(int *p, int *q)
{
    int t;
    t = *p;
    *p = *q;
    *q = t;
}

void vsetc(TCCState *st, CType *type, int r, CValue *vc)
{
    int v;

    if (vtop >= vstack + (VSTACK_SIZE - 1))
       tcc_error(st, "memory full");
    /* cannot let cpu flags if other instruction are generated. Also
       avoid leaving VT_JMP anywhere except on the top of the stack
       because it would complicate the code generator. */
    if (vtop >= vstack) {
        v = vtop->r & VT_VALMASK;
        if (v == VT_CMP || (v & ~1) == VT_JMP)
            gv(st, RC_INT);
    }
    vtop++;
    vtop->type = *type;
    vtop->r = r;
    vtop->r2 = VT_CONST;
    vtop->c = *vc;
}

/* push integer constant */
void vpushi(TCCState *st, int v)
{
    CValue cval;
    cval.i = v;
    vsetc(st, &int_type, VT_CONST, &cval);
}

/* Return a static symbol pointing to a section */
static Sym *get_sym_ref(TCCState *st, CType *type, Section *sec, 
                        unsigned long offset, unsigned long size)
{
    int v;
    Sym *sym;

    v = anon_sym++;
    sym = global_identifier_push(st, v, type->t | VT_STATIC, 0);
    sym->type.ref = type->ref;
    sym->r = VT_CONST | VT_SYM;
    put_extern_sym(st, sym, sec, offset, size);
    return sym;
}

/* push a reference to a section offset by adding a dummy symbol */
static void vpush_ref(TCCState *s, CType *type, Section *sec, unsigned long offset, unsigned long size)
{
    CValue cval;

    cval.ul = 0;
    vsetc(s, type, VT_CONST | VT_SYM, &cval);
    vtop->sym = get_sym_ref(s, type, sec, offset, size);
}

/* define a new external reference to a symbol 'v' of type 'u' */
static Sym *external_global_sym(TCCState * st, int v, CType *type, int r)
{
    Sym *s;

    s = sym_find(st, v);
    if (!s) {
        /* push forward reference */
        s = global_identifier_push(st, v, type->t | VT_EXTERN, 0);
        s->type.ref = type->ref;
        s->r = r | VT_CONST | VT_SYM;
    }
    return s;
}

/* define a new external reference to a symbol 'v' of type 'u' */
static Sym *external_sym(TCCState *st, int v, CType *type, int r)
{
    Sym *s;

    s = sym_find(st, v);
    if (!s) {
        /* push forward reference */
        s = sym_push(st, v, type, r | VT_CONST | VT_SYM, 0);
        s->type.t |= VT_EXTERN;
    } else {
        if (!is_compatible_types(st, &s->type, type))
           tcc_error(st, "incompatible types for redefinition of '%s'", 
                  get_tok_str(st, v, NULL));
    }
    return s;
}

/* push a reference to global symbol v */
static void vpush_global_sym(TCCState *st, CType *type, int v)
{
    Sym *sym;
    CValue cval;

    sym = external_global_sym(st, v, type, 0);
    cval.ul = 0;
    vsetc(st, type, VT_CONST | VT_SYM, &cval);
    vtop->sym = sym;
}

void vset(TCCState *st, CType *type, int r, int v)
{
    CValue cval;

    cval.i = v;
    vsetc(st, type, r, &cval);
}

void vseti(TCCState *st, int r, int v)
{
    CType type;
    type.t = VT_INT;
    vset(st, &type, r, v);
}

void vswap(TCCState *st)
{
    SValue tmp;

    tmp = vtop[0];
    vtop[0] = vtop[-1];
    vtop[-1] = tmp;
}

void vpushv(TCCState *st, SValue *v)
{
    if (vtop >= vstack + (VSTACK_SIZE - 1))
       tcc_error(st, "memory full");
    vtop++;
    *vtop = *v;
}

void vdup(TCCState *st)
{
    vpushv(st, vtop);
}

/* save r to the memory stack, and mark it as being free */
void save_reg(TCCState *st, int r)
{
    int l, saved, size, align;
    SValue *p, sv;
    CType *type;

    /* modify all stack values */
    saved = 0;
    l = 0;
    for(p=vstack;p<=vtop;p++) {
        if ((p->r & VT_VALMASK) == r ||
            ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r))
        {
            /* must save value on stack if not already done */
            if (!saved) {
                /* NOTE: must reload 'r' because r might be equal to r2 */
                r = p->r & VT_VALMASK;
                /* store register in the stack */
                type = &p->type;
                if ((p->r & VT_LVAL) || 
                    (!is_float(st, type->t) && (type->t & VT_BTYPE) != VT_LLONG))
                    type = &int_type;
                size = type_size(st, type, &align);
                loc = (loc - size) & -align;
                sv.type.t = type->t;
                sv.r = VT_LOCAL | VT_LVAL;
                sv.c.ul = loc;
                store(st, r, &sv);
#ifdef TCC_TARGET_I386
                /* x86 specific: need to pop fp register ST0 if saved */
                if (r == TREG_ST0) {
                    o(st, 0xd9dd); /* fstp %st(1) */
                }
#endif
                /* special long long case */
                if ((type->t & VT_BTYPE) == VT_LLONG) {
                    sv.c.ul += 4;
                    store(st, p->r2, &sv);
                }
                l = loc;
                saved = 1;
            }
            /* mark that stack entry as being saved on the stack */
            if (p->r & VT_LVAL) {
                /* also clear the bounded flag because the
                   relocation address of the function was stored in
                   p->c.ul */
                p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
            } else {
                p->r = lvalue_type(st, p->type.t) | VT_LOCAL;
            }
            p->r2 = VT_CONST;
            p->c.ul = l;
        }
    }
}

/* find a register of class 'rc2' with at most one reference on stack.
 * If none, call get_reg(rc) */
int get_reg_ex(TCCState *st, int rc, int rc2) 
{
    int r;
    SValue *p;
    
    for(r=0;r<NB_REGS;r++) {
        if (reg_classes[r] & rc2) {
            int n;
            n=0;
            for(p = vstack; p <= vtop; p++) {
                if ((p->r & VT_VALMASK) == r ||
                    (p->r2 & VT_VALMASK) == r)
                    n++;
            }
            if (n <= 1)
                return r;
        }
    }
    return get_reg(st, rc);
}

/* find a free register of class 'rc'. If none, save one register */
int get_reg(TCCState *st, int rc)
{
    int r;
    SValue *p;

    /* find a free register */
    for(r=0;r<NB_REGS;r++) {
        if (reg_classes[r] & rc) {
            for(p=vstack;p<=vtop;p++) {
                if ((p->r & VT_VALMASK) == r ||
                    (p->r2 & VT_VALMASK) == r)
                    goto notfound;
            }
            return r;
        }
    notfound: ;
    }
    
    /* no register left : free the first one on the stack (VERY
       IMPORTANT to start from the bottom to ensure that we don't
       spill registers used in gen_opi()) */
    for(p=vstack;p<=vtop;p++) {
        r = p->r & VT_VALMASK;
        if (r < VT_CONST && (reg_classes[r] & rc))
            goto save_found;
        /* also look at second register (if long long) */
        r = p->r2 & VT_VALMASK;
        if (r < VT_CONST && (reg_classes[r] & rc)) {
        save_found:
            save_reg(st, r);
            return r;
        }
    }
    /* Should never comes here */
    return -1;
}

/* save registers up to (vtop - n) stack entry */
void save_regs(TCCState *st, int n)
{
    int r;
    SValue *p, *p1;
    p1 = vtop - n;
    for(p = vstack;p <= p1; p++) {
        r = p->r & VT_VALMASK;
        if (r < VT_CONST) {
            save_reg(st, r);
        }
    }
}

/* move register 's' to 'r', and flush previous value of r to memory
   if needed */
void move_reg(TCCState *st, int r, int s)
{
    SValue sv;

    if (r != s) {
        save_reg(st, r);
        sv.type.t = VT_INT;
        sv.r = s;
        sv.c.ul = 0;
        load(st, r, &sv);
    }
}

/* get address of vtop (vtop MUST BE an lvalue) */
void gaddrof(TCCState *st)
{
    vtop->r &= ~VT_LVAL;
    /* tricky: if saved lvalue, then we can go back to lvalue */
    if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
        vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
}

#if 0
/* generate lvalue bound code */
void gbound(TCCState *st)
{
    int lval_type;
    CType type1;

    vtop->r &= ~VT_MUSTBOUND;
    /* if lvalue, then use checking code before dereferencing */
    if (vtop->r & VT_LVAL) {
        /* if not VT_BOUNDED value, then make one */
        if (!(vtop->r & VT_BOUNDED)) {
            lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
            /* must save type because we must set it to int to get pointer */
            type1 = vtop->type;
            vtop->type.t = VT_INT;
            gaddrof(st );
            vpushi(st, 0);
            gen_bounded_ptr_add(st);
            vtop->r |= lval_type;
            vtop->type = type1;
        }
        /* then check for dereferencing */
        gen_bounded_ptr_deref(st);
    }
}
#endif

/* store vtop a register belonging to class 'rc'. lvalues are
   converted to values. Cannot be used if cannot be converted to
   register value (such as structures). */
int gv(TCCState *st, int rc)
{
    int r, r2, rc2, bit_pos, bit_size, size, align, i;
    unsigned long long ll;

    /* NOTE: get_reg can modify vstack[] */
    if (vtop->type.t & VT_BITFIELD) {
        bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
        bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
        /* remove bit field info to avoid loops */
        vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
        /* generate shifts */
        vpushi(st, 32 - (bit_pos + bit_size));
        gen_op(st, TOK_SHL);
        vpushi(st, 32 - bit_size);
        /* NOTE: transformed to SHR if unsigned */
        gen_op(st, TOK_SAR);
        r = gv(st, rc);
    } else {
        if (is_float(st, vtop->type.t) && 
            (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
            Sym *sym;
            int *ptr;
            unsigned long offset;
#if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
            CValue check;
#endif
            
            /* XXX: unify with initializers handling ? */
            /* CPUs usually cannot use float constants, so we store them
               generically in data segment */
            size = type_size(st, &vtop->type, &align);
            offset = (data_section->data_offset + align - 1) & -align;
            data_section->data_offset = offset;
            /* XXX: not portable yet */
#ifdef __i386__
            /* long doubles are defined to be 96 bit wide by
               the i386 ABI but the x87 only uses the first 80. The rest
               is filled with garbage by now, so clear it before writing */
            if(size == 12)
                vtop->c.tab[2] &= 0xffff;
#endif
            ptr = section_ptr_add(st, data_section, size);
            size = size >> 2;
#if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
            check.d = 1;
            if(check.tab[0])
                for(i=0;i<size;i++)
                    ptr[i] = vtop->c.tab[size-1-i];
            else
#endif
            for(i=0;i<size;i++)
                ptr[i] = vtop->c.tab[i];
            sym = get_sym_ref(st, &vtop->type, data_section, offset, size << 2);
            vtop->r |= VT_LVAL | VT_SYM;
            vtop->sym = sym;
            vtop->c.ul = 0;
        }
#if 0
        if (vtop->r & VT_MUSTBOUND) 
            gbound(st );
#endif

        r = vtop->r & VT_VALMASK;
        /* need to reload if:
           - constant
           - lvalue (need to dereference pointer)
           - already a register, but not in the right class */
        if (r >= VT_CONST || 
            (vtop->r & VT_LVAL) ||
            !(reg_classes[r] & rc) ||
            ((vtop->type.t & VT_BTYPE) == VT_LLONG && 
             !(reg_classes[vtop->r2] & rc))) {
            r = get_reg(st, rc);
            if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
                /* two register type load : expand to two words
                   temporarily */
                if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
                    /* load constant */
                    ll = vtop->c.ull;
                    vtop->c.ui = ll; /* first word */
                    load(st, r, vtop);
                    vtop->r = r; /* save register value */
                    vpushi(st, ll >> 32); /* second word */
                } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
                           (vtop->r & VT_LVAL)) {
                    /* We do not want to modifier the long long
                       pointer here, so the safest (and less
                       efficient) is to save all the other registers
                       in the stack. XXX: totally inefficient. */
                    save_regs(st, 1);
                    /* load from memory */
                    load(st, r, vtop);
                    vdup(st);
                    vtop[-1].r = r; /* save register value */
                    /* increment pointer to get second word */
                    vtop->type.t = VT_INT;
                    gaddrof(st);
                    vpushi(st, 4);
                    gen_op(st, '+');
                    vtop->r |= VT_LVAL;
                } else {
                    /* move registers */
                    load(st, r, vtop);
                    vdup(st );
                    vtop[-1].r = r; /* save register value */
                    vtop->r = vtop[-1].r2;
                }
                /* allocate second register */
                rc2 = RC_INT;
                if (rc == RC_IRET)
                    rc2 = RC_LRET;
                r2 = get_reg(st, rc2);
                load(st, r2, vtop);
                vpop(st);
                /* write second register */
                vtop->r2 = r2;
            } else if ((vtop->r & VT_LVAL) && !is_float(st, vtop->type.t)) {
                int t1, t;
                /* lvalue of scalar type : need to use lvalue type
                   because of possible cast */
                t = vtop->type.t;
                t1 = t;
                /* compute memory access type */
                if (vtop->r & VT_LVAL_BYTE)
                    t = VT_BYTE;
                else if (vtop->r & VT_LVAL_SHORT)
                    t = VT_SHORT;
                if (vtop->r & VT_LVAL_UNSIGNED)
                    t |= VT_UNSIGNED;
                vtop->type.t = t;
                load(st, r, vtop);
                /* restore wanted type */
                vtop->type.t = t1;
            } else {
                /* one register type load */
                load(st, r, vtop);
            }
        }
        vtop->r = r;
#ifdef TCC_TARGET_C67
        /* uses register pairs for doubles */
        if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) 
            vtop->r2 = r+1;
#endif
    }
    return r;
}

/* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
void gv2(TCCState *st, int rc1, int rc2)
{
    int v;

    /* generate more generic register first. But VT_JMP or VT_CMP
       values must be generated first in all cases to avoid possible
       reload errors */
    v = vtop[0].r & VT_VALMASK;
    if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
        vswap(st);
        gv(st, rc1);
        vswap(st);
        gv(st, rc2);
        /* test if reload is needed for first register */
        if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
            vswap(st);
            gv(st, rc1);
            vswap(st);
        }
    } else {
        gv(st, rc2);
        vswap(st);
        gv(st, rc1);
        vswap(st);
        /* test if reload is needed for first register */
        if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
            gv(st, rc2);
        }
    }
}

/* expand long long on stack in two int registers */
void lexpand(TCCState *st)
{
    int u;

    u = vtop->type.t & VT_UNSIGNED;
    gv(st, RC_INT);
    vdup(st);
    vtop[0].r = vtop[-1].r2;
    vtop[0].r2 = VT_CONST;
    vtop[-1].r2 = VT_CONST;
    vtop[0].type.t = VT_INT | u;
    vtop[-1].type.t = VT_INT | u;
}

#ifdef TCC_TARGET_ARM
/* expand long long on stack */
void lexpand_nr(void)
{
    int u,v;

    u = vtop->type.t & VT_UNSIGNED;
    vdup(st);
    vtop->r2 = VT_CONST;
    vtop->type.t = VT_INT | u;
    v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
    if (v == VT_CONST) {
      vtop[-1].c.ui = vtop->c.ull;
      vtop->c.ui = vtop->c.ull >> 32;
      vtop->r = VT_CONST;
    } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
      vtop->c.ui += 4;
      vtop->r = vtop[-1].r;
    } else if (v > VT_CONST) {
      vtop--;
      lexpand(st);
    } else
      vtop->r = vtop[-1].r2;
    vtop[-1].r2 = VT_CONST;
    vtop[-1].type.t = VT_INT | u;
}
#endif

/* build a long long from two ints */
void lbuild(TCCState *st, int t)
{
    gv2(st, RC_INT, RC_INT);
    vtop[-1].r2 = vtop[0].r;
    vtop[-1].type.t = t;
    vpop(st);
}

/* rotate n first stack elements to the bottom 
   I1 ... In -> I2 ... In I1 [top is right]
*/
void vrotb(TCCState *s, int n)
{
    int i;
    SValue tmp;

    tmp = vtop[-n + 1];
    for(i=-n+1;i!=0;i++)
        vtop[i] = vtop[i+1];
    vtop[0] = tmp;
}

/* rotate n first stack elements to the top 
   I1 ... In -> In I1 ... I(n-1)  [top is right]
 */
void vrott(TCCState *s, int n)
{
    int i;
    SValue tmp;

    tmp = vtop[0];
    for(i = 0;i < n - 1; i++)
        vtop[-i] = vtop[-i - 1];
    vtop[-n + 1] = tmp;
}

#ifdef TCC_TARGET_ARM
/* like vrott but in other direction
   In ... I1 -> I(n-1) ... I1 In  [top is right]
 */
void vnrott(TCCState *s, int n)
{
    int i;
    SValue tmp;

    tmp = vtop[-n + 1];
    for(i = n - 1; i > 0; i--)
        vtop[-i] = vtop[-i + 1];
    vtop[0] = tmp;
}
#endif

/* pop stack value */
void vpop(TCCState *st)
{
    int v;
    v = vtop->r & VT_VALMASK;
#ifdef TCC_TARGET_I386
    /* for x86, we need to pop the FP stack */
    if (v == TREG_ST0) {
        o(st, 0xd9dd); /* fstp %st(1) */
    } else
#endif
    if (v == VT_JMP || v == VT_JMPI) {
        /* need to put correct jump if && or || without test */
        gsym(vtop->c.ul);
    }
    vtop--;
}

/* convert stack entry to register and duplicate its value in another
   register */
void gv_dup(TCCState *st)
{
    int rc, t, r, r1;
    SValue sv;

    t = vtop->type.t;
    if ((t & VT_BTYPE) == VT_LLONG) {
        lexpand(st);
        gv_dup(st);
        vswap(st);
        vrotb(st, 3);
        gv_dup(st);
        vrotb(st, 4);
        /* stack: H L L1 H1 */
        lbuild(st, t);
        vrotb(st, 3);
        vrotb(st, 3);
        vswap(st);
        lbuild(st, t);
        vswap(st);
    } else {
        /* duplicate value */
        rc = RC_INT;
        sv.type.t = VT_INT;
        if (is_float(st, t)) {
            rc = RC_FLOAT;
            sv.type.t = t;
        }
        r = gv(st, rc);
        r1 = get_reg(st, rc);
        sv.r = r;
        sv.c.ul = 0;
        load(st, r1, &sv); /* move r to r1 */
        vdup(st);
        /* duplicates value */
        vtop->r = r1;
    }
}

/* generate CPU independent (unsigned) long long operations */
void gen_opl(TCCState *st, int op)
{
    int t, a, b, op1, c, i;
    int func;
    SValue tmp;

    switch(op) {
    case '/':
    case TOK_PDIV:
        func = TOK___divdi3;
        goto gen_func;
    case TOK_UDIV:
        func = TOK___udivdi3;
        goto gen_func;
    case '%':
        func = TOK___moddi3;
        goto gen_func;
    case TOK_UMOD:
        func = TOK___umoddi3;
    gen_func:
        /* call generic long long function */
        vpush_global_sym(st, &func_old_type, func);
        vrott(st, 3);
        gfunc_call(st, 2);
        vpushi(st, 0);
        vtop->r = REG_IRET;
        vtop->r2 = REG_LRET;
        break;
    case '^':
    case '&':
    case '|':
    case '*':
    case '+':
    case '-':
        t = vtop->type.t;
        vswap(st);
        lexpand(st);
        vrotb(st, 3);
        lexpand(st);
        /* stack: L1 H1 L2 H2 */
        tmp = vtop[0];
        vtop[0] = vtop[-3];
        vtop[-3] = tmp;
        tmp = vtop[-2];
        vtop[-2] = vtop[-3];
        vtop[-3] = tmp;
        vswap(st);
        /* stack: H1 H2 L1 L2 */
        if (op == '*') {
            vpushv(st, vtop - 1);
            vpushv(st, vtop - 1);
            gen_op(st, TOK_UMULL);
            lexpand(st);
            /* stack: H1 H2 L1 L2 ML MH */
            for(i=0;i<4;i++)
                vrotb(st, 6);
            /* stack: ML MH H1 H2 L1 L2 */
            tmp = vtop[0];
            vtop[0] = vtop[-2];
            vtop[-2] = tmp;
            /* stack: ML MH H1 L2 H2 L1 */
            gen_op(st, '*');
            vrotb(st, 3);
            vrotb(st, 3);
            gen_op(st, '*');
            /* stack: ML MH M1 M2 */
            gen_op(st, '+');
            gen_op(st, '+');
        } else if (op == '+' || op == '-') {
            /* XXX: add non carry method too (for MIPS or alpha) */
            if (op == '+')
                op1 = TOK_ADDC1;
            else
                op1 = TOK_SUBC1;
            gen_op(st, op1);
            /* stack: H1 H2 (L1 op L2) */
            vrotb(st, 3);
            vrotb(st, 3);
            gen_op(st, op1 + 1); /* TOK_xxxC2 */
        } else {
            gen_op(st, op);
            /* stack: H1 H2 (L1 op L2) */
            vrotb(st, 3);
            vrotb(st, 3);
            /* stack: (L1 op L2) H1 H2 */
            gen_op(st, op);
            /* stack: (L1 op L2) (H1 op H2) */
        }
        /* stack: L H */
        lbuild(st, t);
        break;
    case TOK_SAR:
    case TOK_SHR:
    case TOK_SHL:
        if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
            t = vtop[-1].type.t;
            vswap(st);
            lexpand(st);
            vrotb(st, 3);
            /* stack: L H shift */
            c = (int)vtop->c.i;
            /* constant: simpler */
            /* NOTE: all comments are for SHL. the other cases are
               done by swaping words */
            vpop(st);
            if (op != TOK_SHL)
                vswap(st);
            if (c >= 32) {
                /* stack: L H */
                vpop(st);
                if (c > 32) {
                    vpushi(st, c - 32);
                    gen_op(st, op);
                }
                if (op != TOK_SAR) {
                    vpushi(st, 0);
                } else {
                    gv_dup(st);
                    vpushi(st, 31);
                    gen_op(st, TOK_SAR);
                }
                vswap(st);
            } else {
                vswap(st);
                gv_dup(st);
                /* stack: H L L */
                vpushi(st, c);
                gen_op(st, op);
                vswap(st);
                vpushi(st, 32 - c);
                if (op == TOK_SHL)
                    gen_op(st, TOK_SHR);
                else
                    gen_op(st, TOK_SHL);
                vrotb(st, 3);
                /* stack: L L H */
                vpushi(st, c);
                if (op == TOK_SHL)
                    gen_op(st, TOK_SHL);
                else
                    gen_op(st, TOK_SHR);
                gen_op(st, '|');
            }
            if (op != TOK_SHL)
                vswap(st);
            lbuild(st, t);
        } else {
            /* XXX: should provide a faster fallback on x86 ? */
            switch(op) {
            case TOK_SAR:
                func = TOK___sardi3;
                goto gen_func;
            case TOK_SHR:
                func = TOK___shrdi3;
                goto gen_func;
            case TOK_SHL:
                func = TOK___shldi3;
                goto gen_func;
            }
        }
        break;
    default:
        /* compare operations */
        t = vtop->type.t;
        vswap(st);
        lexpand(st);
        vrotb(st, 3);
        lexpand(st);
        /* stack: L1 H1 L2 H2 */
        tmp = vtop[-1];
        vtop[-1] = vtop[-2];
        vtop[-2] = tmp;
        /* stack: L1 L2 H1 H2 */
        /* compare high */
        op1 = op;
        /* when values are equal, we need to compare low words. since
           the jump is inverted, we invert the test too. */
        if (op1 == TOK_LT)
            op1 = TOK_LE;
        else if (op1 == TOK_GT)
            op1 = TOK_GE;
        else if (op1 == TOK_ULT)
            op1 = TOK_ULE;
        else if (op1 == TOK_UGT)
            op1 = TOK_UGE;
        a = 0;
        b = 0;
        gen_op(st, op1);
        if (op1 != TOK_NE) {
            a = gtst(st, 1, 0);
        }
        if (op != TOK_EQ) {
            /* generate non equal test */
            /* XXX: NOT PORTABLE yet */
            if (a == 0) {
                b = gtst(st, 0, 0);
            } else {
#if defined(TCC_TARGET_I386)
                b = psym(st, 0x850f, 0);
#elif defined(TCC_TARGET_ARM)
                b = ind;
                o(st, 0x1A000000 | encbranch(ind, 0, 1));
#elif defined(TCC_TARGET_C67)
               tcc_error("not implemented");
#else
#error not supported
#endif
            }
        }
        /* compare low. Always unsigned */
        op1 = op;
        if (op1 == TOK_LT)
            op1 = TOK_ULT;
        else if (op1 == TOK_LE)
            op1 = TOK_ULE;
        else if (op1 == TOK_GT)
            op1 = TOK_UGT;
        else if (op1 == TOK_GE)
            op1 = TOK_UGE;
        gen_op(st, op1);
        a = gtst(st, 1, a);
        gsym(b);
        vseti(st, VT_JMPI, a);
        break;
    }
}

/* handle long long constant and various machine independent optimizations */
void gen_opic(TCCState *st, int op)
{
    int c1, c2, t1, t2;
    SValue *v1, *v2;
    long long l1, l2;

    v1 = vtop - 1;
    v2 = vtop;
    t1 = v1->type.t & VT_BTYPE;
    t2 = v2->type.t & VT_BTYPE;
    l1 = (t1 == VT_LLONG) ? v1->c.ll : v1->c.i;
    l2 = (t2 == VT_LLONG) ? v2->c.ll : v2->c.i;

    /* For forward symbols we can only constify &&, || or == NULL */
    c2 = VT_SYM;
    if (op == TOK_EQ && (v1->c.ll == 0 || v2->c.ll == 0)) c2 = 0;
    if (op == TOK_LAND || op == TOK_LOR) c2 = 0;
    c1 = (v1->r & (VT_VALMASK | VT_LVAL | c2)) == VT_CONST;
    c2 = (v2->r & (VT_VALMASK | VT_LVAL | c2)) == VT_CONST;

    if (c1 && c2) {
        switch(op) {
        case '+': l1 += l2; break;
        case '-': l1 -= l2; break;
        case '&': l1 &= l2; break;
        case '^': l1 ^= l2; break;
        case '|': l1 |= l2; break;
        case '*': l1 *= l2; break;

        case TOK_PDIV:
        case '/':
        case '%':
        case TOK_UDIV:
        case TOK_UMOD:
            /* if division by zero, generate explicit division */
            if (l2 == 0) {
                if (const_wanted)
                   tcc_error(st, "division by zero in constant");
                goto general_case;
            }
            switch(op) {
            default: l1 /= l2; break;
            case '%': l1 %= l2; break;
            case TOK_UDIV: l1 = (unsigned long long)l1 / l2; break;
            case TOK_UMOD: l1 = (unsigned long long)l1 % l2; break;
            }
            break;
        case TOK_SHL: l1 <<= l2; break;
        case TOK_SHR: l1 = (unsigned long long)l1 >> l2; break;
        case TOK_SAR: l1 >>= l2; break;
            /* tests */
        case TOK_ULT: l1 = (unsigned long long)l1 < (unsigned long long)l2; break;
        case TOK_UGE: l1 = (unsigned long long)l1 >= (unsigned long long)l2; break;
        case TOK_EQ: l1 = l1 == l2; break;
        case TOK_NE: l1 = l1 != l2; break;
        case TOK_ULE: l1 = (unsigned long long)l1 <= (unsigned long long)l2; break;
        case TOK_UGT: l1 = (unsigned long long)l1 > (unsigned long long)l2; break;
        case TOK_LT: l1 = l1 < l2; break;
        case TOK_GE: l1 = l1 >= l2; break;
        case TOK_LE: l1 = l1 <= l2; break;
        case TOK_GT: l1 = l1 > l2; break;
            /* logical */
        case TOK_LAND: l1 = l1 && l2; break;
        case TOK_LOR: l1 = l1 || l2; break;
        default:
            goto general_case;
        }
        v1->c.ll = l1;
        vtop--;
    } else {
        /* if commutative ops, put c2 as constant */
        if (c1 && (op == '+' || op == '&' || op == '^' || 
                   op == '|' || op == '*')) {
            vswap(st);
            swap(&c1, &c2);
            l2 = l1;
        }
        /* Filter out NOP operations like x*1, x-0, x&-1... */
        if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV || 
                     op == TOK_PDIV) && 
                    l2 == 1) ||
                   ((op == '+' || op == '-' || op == '|' || op == '^' || 
                     op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) && 
                    l2 == 0) ||
                   (op == '&' && 
                    l2 == -1))) {
            /* nothing to do */
            vtop--;
        } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
            /* try to use shifts instead of muls or divs */
            if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
                int n = -1;
                while (l2) {
                    l2 >>= 1;
                    n++;
                }
                vtop->c.ll = n;
                if (op == '*')
                    op = TOK_SHL;
                else if (op == TOK_PDIV)
                    op = TOK_SAR;
                else
                    op = TOK_SHR;
            }
            goto general_case;
        } else if (c2 && (op == '+' || op == '-') &&
                   (vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == 
                   (VT_CONST | VT_SYM)) {
            /* symbol + constant case */
            if (op == '-')
                l2 = -l2;
            vtop--;
            vtop->c.ll += l2;
        } else {
        general_case:
            /* call low level op generator */
            if (cur_text_section) {
                if (t1 == VT_LLONG|| t2 == VT_LLONG) gen_opl(st, op);
                else gen_opi(st, op);
            } else vtop--;
        }
    }
}

/* generate a floating point operation with constant propagation */
void gen_opif(TCCState *st, int op)
{
    int c1, c2;
    SValue *v1, *v2;
    long double f1, f2;

    v1 = vtop - 1;
    v2 = vtop;
    /* currently, we cannot do computations with forward symbols */
    c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
    c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
    if (c1 && c2) {
        if (v1->type.t == VT_FLOAT) {
            f1 = v1->c.f;
            f2 = v2->c.f;
        } else if (v1->type.t == VT_DOUBLE) {
            f1 = v1->c.d;
            f2 = v2->c.d;
        } else {
            f1 = v1->c.ld;
            f2 = v2->c.ld;
        }

        /* NOTE: we only do constant propagation if finite number (not
           NaN or infinity) (ANSI spec) */
        if (!ieee_finite(st, f1) || !ieee_finite(st, f2))
            goto general_case;

        switch(op) {
        case '+': f1 += f2; break;
        case '-': f1 -= f2; break;
        case '*': f1 *= f2; break;
        case '/': 
            if (f2 == 0.0) {
                if (const_wanted)
                   tcc_error(st, "division by zero in constant");
                goto general_case;
            }
            f1 /= f2; 
            break;
            /* XXX: also handles tests ? */
        default:
            goto general_case;
        }
        /* XXX: overflow test ? */
        if (v1->type.t == VT_FLOAT) {
            v1->c.f = f1;
        } else if (v1->type.t == VT_DOUBLE) {
            v1->c.d = f1;
        } else {
            v1->c.ld = f1;
        }
        vtop--;
    } else {
    general_case:
        if (cur_text_section) gen_opf(st, op);
        else vtop--;
    }
}

static int pointed_size(TCCState *st, CType *type)
{
    int align;
    return type_size(st, pointed_type(st, type), &align);
}

static inline int is_null_pointer(TCCState *st, SValue *p)
{
    if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
        return 0;
    return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
        ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
}

static inline int is_integer_btype(TCCState *st, int bt)
{
    return (bt == VT_BYTE || bt == VT_SHORT || 
            bt == VT_INT || bt == VT_LLONG);
}

/* check types for comparison or substraction of pointers */
static void check_comparison_pointer_types(TCCState *st, SValue *p1, SValue *p2, int op)
{
    CType *type1, *type2, tmp_type1, tmp_type2;
    int bt1, bt2;
    
    /* null pointers are accepted for all comparisons as gcc */
    if (is_null_pointer(st, p1) || is_null_pointer(st, p2))
        return;
    type1 = &p1->type;
    type2 = &p2->type;
    bt1 = type1->t & VT_BTYPE;
    bt2 = type2->t & VT_BTYPE;
    /* accept comparison between pointer and integer with a warning */
    if ((is_integer_btype(st, bt1) || is_integer_btype(st, bt2)) && op != '-') {
        if (op != TOK_LOR && op != TOK_LAND )
            warning(st, "comparison between pointer and integer");
        return;
    }

    /* both must be pointers or implicit function pointers */
    if (bt1 == VT_PTR) {
        type1 = pointed_type(st, type1);
    } else if (bt1 != VT_FUNC) 
        goto invalid_operands;

    if (bt2 == VT_PTR) {
        type2 = pointed_type(st, type2);
    } else if (bt2 != VT_FUNC) { 
    invalid_operands:
       tcc_error(st, "invalid operands to binary %s", get_tok_str(st, op, NULL));
    }
    if ((type1->t & VT_BTYPE) == VT_VOID || 
        (type2->t & VT_BTYPE) == VT_VOID)
        return;
    tmp_type1 = *type1;
    tmp_type2 = *type2;
    tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
    tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
    if (!is_compatible_types(st, &tmp_type1, &tmp_type2)) {
        /* gcc-like error if '-' is used */
        if (op == '-')
            goto invalid_operands;
        else
            warning(st, "comparison of distinct pointer types lacks a cast");
    }
}

/* generic gen_op: handles types problems */
void gen_op(TCCState *st, int op)
{
    int u, t1, t2, bt1, bt2, t;
    CType type1;

    t1 = vtop[-1].type.t;
    t2 = vtop[0].type.t;
    bt1 = t1 & VT_BTYPE;
    bt2 = t2 & VT_BTYPE;

    if (bt1 == VT_PTR || bt2 == VT_PTR) {
        /* at least one operand is a pointer */
        /* relationnal op: must be both pointers */
        if (op >= TOK_ULT && op <= TOK_LOR) {
            check_comparison_pointer_types(st, vtop - 1, vtop, op);
            /* pointers are handled are unsigned */
            t = VT_INT | VT_UNSIGNED;
            goto std_op;
        }
        /* if both pointers, then it must be the '-' op */
        if (bt1 == VT_PTR && bt2 == VT_PTR) {
            if (op != '-')
               tcc_error(st, "cannot use pointers here");
            check_comparison_pointer_types(st, vtop - 1, vtop, op);
            /* XXX: check that types are compatible */
            u = pointed_size(st, &vtop[-1].type);
            gen_opic(st, op);
            /* set to integer type */
            vtop->type.t = VT_INT; 
            vpushi(st, u);
            gen_op(st, TOK_PDIV);
        } else {
            /* exactly one pointer : must be '+' or '-'. */
            if (op != '-' && op != '+')
               tcc_error(st, "cannot use pointers here");
            /* Put pointer as first operand */
            if (bt2 == VT_PTR) {
                vswap(st);
                swap(&t1, &t2);
            }
            type1 = vtop[-1].type;
            /* XXX: cast to int ? (long long case) */
            vpushi(st, pointed_size(st, &vtop[-1].type));
            gen_op(st, '*');
#if 0
            /* if evaluating constant expression, no code should be
               generated, so no bound check */
            if (do_bounds_check && !const_wanted) {
                /* if bounded pointers, we generate a special code to
                   test bounds */
                if (op == '-') {
                    vpushi(st, 0);
                    vswap(st);
                    gen_op(st, '-');
                }
                gen_bounded_ptr_add(st);
            } else
#endif
            {
                gen_opic(st, op);
            }
            /* put again type if gen_opic(st) swaped operands */
            vtop->type = type1;
        }
    } else if (is_float(st, bt1) || is_float(st, bt2)) {
        /* compute bigger type and do implicit casts */
        if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
            t = VT_LDOUBLE;
        } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
            t = VT_DOUBLE;
        } else {
            t = VT_FLOAT;
        }
        /* floats can only be used for a few operations */
        if (op != '+' && op != '-' && op != '*' && op != '/' &&
            (op < TOK_ULT || op > TOK_GT))
           tcc_error(st, "invalid operands for binary operation");
        goto std_op;
    } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
        /* cast to biggest op */
        t = VT_LLONG;
        /* convert to unsigned if it does not fit in a long long */
        if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
            (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
            t |= VT_UNSIGNED;
        goto std_op;
    } else {
        /* integer operations */
        t = VT_INT;
        /* convert to unsigned if it does not fit in an integer */
        if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
            (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
            t |= VT_UNSIGNED;
    std_op:
        /* XXX: currently, some unsigned operations are explicit, so
           we modify them here */
        if (t & VT_UNSIGNED) {
            if (op == TOK_SAR)
                op = TOK_SHR;
            else if (op == '/')
                op = TOK_UDIV;
            else if (op == '%')
                op = TOK_UMOD;
            else if (op == TOK_LT)
                op = TOK_ULT;
            else if (op == TOK_GT)
                op = TOK_UGT;
            else if (op == TOK_LE)
                op = TOK_ULE;
            else if (op == TOK_GE)
                op = TOK_UGE;
        }
        vswap(st);
        type1.t = t;
        gen_cast(st, &type1);
        vswap(st);
        /* special case for shifts and long long: we keep the shift as
           an integer */
        if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
            type1.t = VT_INT;
        gen_cast(st, &type1);
        if (is_float(st, t))
            gen_opif(st, op);
        else
            gen_opic(st, op);
        if (op >= TOK_ULT && op <= TOK_GT) {
            /* relationnal op: the result is an int */
            vtop->type.t = VT_INT;
        } else {
            vtop->type.t = t;
        }
    }
}

/* generic itof for unsigned long long case */
void gen_cvt_itof1(TCCState *st, int t)
{
    if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) == 
        (VT_LLONG | VT_UNSIGNED)) {

        if (t == VT_FLOAT)
            vpush_global_sym(st, &func_old_type, TOK___ulltof);
        else if (t == VT_DOUBLE)
            vpush_global_sym(st, &func_old_type, TOK___ulltod);
        else
            vpush_global_sym(st, &func_old_type, TOK___ulltold);
        vrott(st, 2);
        gfunc_call(st, 1);
        vpushi(st, 0);
        vtop->r = REG_FRET;
    } else {
        gen_cvt_itof(st, t);
    }
}

/* generic ftoi for unsigned long long case */
void gen_cvt_ftoi1(TCCState *state, int t)
{
    int st;

    if (t == (VT_LLONG | VT_UNSIGNED)) {
        /* not handled natively */
        st = vtop->type.t & VT_BTYPE;
        if (st == VT_FLOAT)
            vpush_global_sym(state, &func_old_type, TOK___fixunssfdi);
        else if (st == VT_DOUBLE)
            vpush_global_sym(state, &func_old_type, TOK___fixunsdfdi);
        else
            vpush_global_sym(state, &func_old_type, TOK___fixunsxfdi);
        vrott(state, 2);
        gfunc_call(state, 1);
        vpushi(state, 0);
        vtop->r = REG_IRET;
        vtop->r2 = REG_LRET;
    } else {
        gen_cvt_ftoi(state, t);
    }
}

/* force char or short cast */
void force_charshort_cast(TCCState *st, int t)
{
    int bits, dbt;
    dbt = t & VT_BTYPE;
    /* XXX: add optimization if lvalue : just change type and offset */
    if (dbt == VT_BYTE)
        bits = 8;
    else
        bits = 16;
    if (t & VT_UNSIGNED) {
        vpushi(st, (1 << bits) - 1);
        gen_op(st, '&');
    } else {
        bits = 32 - bits;
        vpushi(st, bits);
        gen_op(st, TOK_SHL);
        /* result must be signed or the SAR is converted to an SHL
           This was not the case when "t" was a signed short
           and the last value on the stack was an unsigned int
        */
        vtop->type.t &= (~VT_UNSIGNED);
        vpushi(st, bits);
        gen_op(st, TOK_SAR);
    }
}

/* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
static void gen_cast(TCCState *st, CType *type)
{
    int sbt, dbt, sf, df, c;

    /* special delayed cast for char/short */
    /* XXX: in some cases (multiple cascaded casts), it may still
       be incorrect */
    if (vtop->r & VT_MUSTCAST) {
        vtop->r &= ~VT_MUSTCAST;
        force_charshort_cast(st, vtop->type.t);
    }

    /* bitfields first get cast to ints */
    if (vtop->type.t & VT_BITFIELD) {
        gv(st, RC_INT);
    }

    dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
    sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);

    if (sbt != dbt && cur_text_section) {
        sf = is_float(st, sbt);
        df = is_float(st, dbt);
        c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
        if (sf && df) {
            /* convert from fp to fp */
            if (c) {
                /* constant case: we can do it now */
                /* XXX: in ISOC, cannot do it if error in convert */
                if (dbt == VT_FLOAT && sbt == VT_DOUBLE) 
                    vtop->c.f = (float)vtop->c.d;
                else if (dbt == VT_FLOAT && sbt == VT_LDOUBLE) 
                    vtop->c.f = (float)vtop->c.ld;
                else if (dbt == VT_DOUBLE && sbt == VT_FLOAT) 
                    vtop->c.d = (double)vtop->c.f;
                else if (dbt == VT_DOUBLE && sbt == VT_LDOUBLE) 
                    vtop->c.d = (double)vtop->c.ld;
                else if (dbt == VT_LDOUBLE && sbt == VT_FLOAT) 
                    vtop->c.ld = (long double)vtop->c.f;
                else if (dbt == VT_LDOUBLE && sbt == VT_DOUBLE) 
                    vtop->c.ld = (long double)vtop->c.d;
            } else {
                /* non constant case: generate code */
                gen_cvt_ftof(st, dbt);
            }
        } else if (df) {
            /* convert int to fp */
            if (c) {
                switch(sbt) {
                case VT_LLONG | VT_UNSIGNED:
                case VT_LLONG:
                    /* XXX: add const cases for long long */
                    goto do_itof;
                case VT_INT | VT_UNSIGNED:
                    switch(dbt) {
                    case VT_FLOAT: vtop->c.f = (float)vtop->c.ui; break;
                    case VT_DOUBLE: vtop->c.d = (double)vtop->c.ui; break;
                    case VT_LDOUBLE: vtop->c.ld = (long double)vtop->c.ui; break;
                    }
                    break;
                default:
                    switch(dbt) {
                    case VT_FLOAT: vtop->c.f = (float)vtop->c.i; break;
                    case VT_DOUBLE: vtop->c.d = (double)vtop->c.i; break;
                    case VT_LDOUBLE: vtop->c.ld = (long double)vtop->c.i; break;
                    }
                    break;
                }
            } else {
            do_itof:
#if !defined(TCC_TARGET_ARM)
                gen_cvt_itof1(st, dbt);
#else
                gen_cvt_itof(st, dbt);
#endif
            }
        } else if (sf) {
            /* convert fp to int */
            if (dbt == VT_BOOL) {
                 vpushi(st, 0);
                 gen_op(st, TOK_NE);
            } else {
                /* we handle char/short/etc... with generic code */
                if (dbt != (VT_INT | VT_UNSIGNED) &&
                    dbt != (VT_LLONG | VT_UNSIGNED) &&
                    dbt != VT_LLONG)
                    dbt = VT_INT;
                if (c) {
                    switch(dbt) {
                    case VT_LLONG | VT_UNSIGNED:
                    case VT_LLONG:
                        /* XXX: add const cases for long long */
                        goto do_ftoi;
                    case VT_INT | VT_UNSIGNED:
                        switch(sbt) {
                        case VT_FLOAT: vtop->c.ui = (unsigned int)vtop->c.d; break;
                        case VT_DOUBLE: vtop->c.ui = (unsigned int)vtop->c.d; break;
                        case VT_LDOUBLE: vtop->c.ui = (unsigned int)vtop->c.d; break;
                        }
                        break;
                    default:
                        /* int case */
                        switch(sbt) {
                        case VT_FLOAT: vtop->c.i = (int)vtop->c.d; break;
                        case VT_DOUBLE: vtop->c.i = (int)vtop->c.d; break;
                        case VT_LDOUBLE: vtop->c.i = (int)vtop->c.d; break;
                        }
                        break;
                    }
                } else {
                do_ftoi:
                    gen_cvt_ftoi1(st, dbt);
                }
                if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
                    /* additional cast for char/short... */
                    vtop->type.t = dbt;
                    gen_cast(st, type);
                }
            }
        } else if ((dbt & VT_BTYPE) == VT_LLONG) {
            if ((sbt & VT_BTYPE) != VT_LLONG) {
                /* scalar to long long */
                if (c) {
                    if (sbt == (VT_INT | VT_UNSIGNED))
                        vtop->c.ll = vtop->c.ui;
                    else
                        vtop->c.ll = vtop->c.i;
                } else {
                    /* machine independent conversion */
                    gv(st, RC_INT);
                    /* generate high word */
                    if (sbt == (VT_INT | VT_UNSIGNED)) {
                        vpushi(st, 0);
                        gv(st, RC_INT);
                    } else {
                        gv_dup(st);
                        vpushi(st, 31);
                        gen_op(st, TOK_SAR);
                    }
                    /* patch second register */
                    vtop[-1].r2 = vtop->r;
                    vpop(st);
                }
            }
        } else if (dbt == VT_BOOL) {
            /* scalar to bool */
            vpushi(st, 0);
            gen_op(st, TOK_NE);
        } else if ((dbt & VT_BTYPE) == VT_BYTE || 
                   (dbt & VT_BTYPE) == VT_SHORT) {
            if (sbt == VT_PTR) {
                vtop->type.t = VT_INT;
                warning(st, "nonportable conversion from pointer to char/short");
            }
            force_charshort_cast(st, dbt);
        } else if ((dbt & VT_BTYPE) == VT_INT) {
            /* scalar to int */
            if (sbt == VT_LLONG) {
                /* from long long: just take low order word */
                lexpand(st);
                vpop(st);
            } 
            /* if lvalue and single word type, nothing to do because
               the lvalue already contains the real type size (see
               VT_LVAL_xxx constants) */
        }
    } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
        /* if we are casting between pointer types,
           we must update the VT_LVAL_xxx size */
        vtop->r = (vtop->r & ~VT_LVAL_TYPE)
                  | (lvalue_type(st, type->ref->type.t) & VT_LVAL_TYPE);
    }
    vtop->type = *type;
}

/* return type size. Put alignment at 'a' */
static int type_size(TCCState *st, CType *type, int *a)
{
    Sym *s;
    int bt;

    bt = type->t & VT_BTYPE;
    if (bt == VT_STRUCT) {
        /* struct/union */
        s = type->ref;
        *a = s->r;
        return s->c;
    } else if (bt == VT_PTR) {
        if (type->t & VT_ARRAY) {
            s = type->ref;
            return type_size(st, &s->type, a) * s->c;
        } else {
            *a = PTR_SIZE;
            return PTR_SIZE;
        }
    } else if (bt == VT_LDOUBLE) {
        *a = LDOUBLE_ALIGN;
        return LDOUBLE_SIZE;
    } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
#ifdef TCC_TARGET_I386
        *a = 4;
#elif defined(TCC_TARGET_ARM)
#ifdef TCC_ARM_EABI
        *a = 8;
#else
        *a = 4;
#endif
#else
        *a = 8;
#endif
        return 8;
    } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
        *a = 4;
        return 4;
    } else if (bt == VT_SHORT) {
        *a = 2;
        return 2;
    } else {
        /* char, void, function, _Bool */
        *a = 1;
        return 1;
    }
}

/* return the pointed type of t */
static inline CType *pointed_type(TCCState *st, CType *type)
{
    return &type->ref->type;
}

/* modify type so that its it is a pointer to type. */
static void mk_pointer(TCCState *st, CType *type)
{
    Sym *s;
    s = sym_push(st, SYM_FIELD, type, 0, -1);
    type->t = VT_PTR | (type->t & ~VT_TYPE);
    type->ref = s;
}

/* compare function types. OLD functions match any new functions */
static int is_compatible_func(TCCState *state, CType *type1, CType *type2)
{
    Sym *st, *s2;

    st = type1->ref;
    s2 = type2->ref;
    if (!is_compatible_types(state, &st->type, &s2->type))
        return 0;
    /* check func_call */
    if (st->r != s2->r)
        return 0;
    /* XXX: not complete */
    if (st->c == FUNC_OLD || s2->c == FUNC_OLD)
        return 1;
    if (st->c != s2->c)
        return 0;
    while (st != NULL) {
        if (s2 == NULL)
            return 0;
        if (!is_compatible_types(state, &st->type, &s2->type))
            return 0;
        st = st->next;
        s2 = s2->next;
    }
    if (s2)
        return 0;
    return 1;
}

/* return true if type1 and type2 are exactly the same (including
   qualifiers). 

   - enums are not checked as gcc __builtin_types_compatible_p (st) 
 */
static int is_compatible_types(TCCState *st, CType *type1, CType *type2)
{
    int bt1, t1, t2;

    t1 = type1->t & VT_TYPE;
    t2 = type2->t & VT_TYPE;
    /* XXX: bitfields ? */
    if (t1 != t2)
        return 0;
    /* test more complicated cases */
    bt1 = t1 & VT_BTYPE;
    if (bt1 == VT_PTR) {
        type1 = pointed_type(st, type1);
        type2 = pointed_type(st, type2);
        return is_compatible_types(st, type1, type2);
    } else if (bt1 == VT_STRUCT) {
        return (type1->ref == type2->ref);
    } else if (bt1 == VT_FUNC) {
        return is_compatible_func(st, type1, type2);
    } else {
        return 1;
    }
}

/* print a type. If 'varstr' is not NULL, then the variable is also
   printed in the type */
/* XXX: union */
/* XXX: add array and function pointers */
void type_to_str(TCCState *st, char *buf, int buf_size, 
                 CType *type, const char *varstr)
{
    int bt, v, t;
    Sym *s, *sa;
    char buf1[256];
    const char *tstr;

    t = type->t & VT_TYPE;
    bt = t & VT_BTYPE;
    buf[0] = '\0';
    if (t & VT_CONSTANT)
        pstrcat(st, buf, buf_size, "const ");
    if (t & VT_VOLATILE)
        pstrcat(st, buf, buf_size, "volatile ");
    if (t & VT_UNSIGNED)
        pstrcat(st, buf, buf_size, "unsigned ");
    switch(bt) {
    case VT_VOID:
        tstr = "void";
        goto add_tstr;
    case VT_BOOL:
        tstr = "_Bool";
        goto add_tstr;
    case VT_BYTE:
        tstr = "char";
        goto add_tstr;
    case VT_SHORT:
        tstr = "short";
        goto add_tstr;
    case VT_INT:
        tstr = "int";
        goto add_tstr;
    case VT_LONG:
        tstr = "long";
        goto add_tstr;
    case VT_LLONG:
        tstr = "long long";
        goto add_tstr;
    case VT_FLOAT:
        tstr = "float";
        goto add_tstr;
    case VT_DOUBLE:
        tstr = "double";
        goto add_tstr;
    case VT_LDOUBLE:
        tstr = "long double";
    add_tstr:
        pstrcat(st, buf, buf_size, tstr);
        break;
    case VT_ENUM:
    case VT_STRUCT:
        if (bt == VT_STRUCT)
            tstr = "struct ";
        else
            tstr = "enum ";
        pstrcat(st, buf, buf_size, tstr);
        v = type->ref->v & ~SYM_STRUCT;
        if (v >= SYM_FIRST_ANOM)
            pstrcat(st, buf, buf_size, "<anonymous>");
        else
            pstrcat(st, buf, buf_size, get_tok_str(st, v, NULL));
        break;
    case VT_FUNC:
        s = type->ref;
        type_to_str(st, buf, buf_size, &s->type, varstr);
        pstrcat(st, buf, buf_size, "(");
        sa = s->next;
        while (sa != NULL) {
            type_to_str(st, buf1, sizeof(buf1), &sa->type, NULL);
            pstrcat(st, buf, buf_size, buf1);
            sa = sa->next;
            if (sa)
                pstrcat(st, buf, buf_size, ", ");
        }
        pstrcat(st, buf, buf_size, ")");
        goto no_var;
    case VT_PTR:
        s = type->ref;
        pstrcpy(st,  buf1, sizeof(buf1), "*");
        if (varstr)
            pstrcat(st, buf1, sizeof(buf1), varstr);
        type_to_str(st, buf, buf_size, &s->type, buf1);
        goto no_var;
    }
    if (varstr) {
        pstrcat(st, buf, buf_size, " ");
        pstrcat(st, buf, buf_size, varstr);
    }
 no_var: ;
}

/* verify type compatibility to store vtop in 'dt' type, and generate
   casts if needed. */
static void gen_assign_cast(TCCState *state, CType *dt)
{
    CType *st, *type1, *type2, tmp_type1, tmp_type2;
    char buf1[256], buf2[256];
    int dbt, sbt;

    st = &vtop->type; /* source type */
    dbt = dt->t & VT_BTYPE;
    sbt = st->t & VT_BTYPE;
    if (dt->t & VT_CONSTANT)
        warning(state, "assignment of read-only location");
    switch(dbt) {
    case VT_PTR:
        /* special cases for pointers */
        /* '0' can also be a pointer */
        if (is_null_pointer(state, vtop))
            goto type_ok;
        /* accept implicit pointer to integer cast with warning */
        if (is_integer_btype(state, sbt)) {
            warning(state, "assignment makes pointer from integer without a cast");
            goto type_ok;
        }
        type1 = pointed_type(state, dt);
        /* a function is implicitely a function pointer */
        if (sbt == VT_FUNC) {
            if ((type1->t & VT_BTYPE) != VT_VOID &&
                !is_compatible_types(state, pointed_type(state, dt), st))
                goto error;
            else
                goto type_ok;
        }
        if (sbt != VT_PTR)
            goto error;
        type2 = pointed_type(state, st);
        if ((type1->t & VT_BTYPE) == VT_VOID || 
            (type2->t & VT_BTYPE) == VT_VOID) {
            /* void * can match anything */
        } else {
            /* exact type match, except for unsigned */
            tmp_type1 = *type1;
            tmp_type2 = *type2;
            tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
            tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
            if (!is_compatible_types(state, &tmp_type1, &tmp_type2))
                warning(state, "assignment from incompatible pointer type");
        }
        /* check const and volatile */
        if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
            (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
            warning(state, "assignment discards qualifiers from pointer target type");
        break;
    case VT_BYTE:
    case VT_SHORT:
    case VT_INT:
    case VT_LLONG:
        if (sbt == VT_PTR || sbt == VT_FUNC) {
            warning(state, "assignment makes integer from pointer without a cast");
        }
        /* XXX: more tests */
        break;
    case VT_STRUCT:
        tmp_type1 = *dt;
        tmp_type2 = *st;
        tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
        tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
        if (!is_compatible_types(state, &tmp_type1, &tmp_type2)) {
        error:
            type_to_str(state, buf1, sizeof(buf1), st, NULL);
            type_to_str(state, buf2, sizeof(buf2), dt, NULL);
           tcc_error(state, "cannot cast '%s' to '%s'", buf1, buf2);
        }
        break;
    }
 type_ok:
    gen_cast(state, dt);
}

/* store vtop in lvalue pushed on stack */
void vstore(TCCState *st)
{
    int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;

    ft = vtop[-1].type.t;
    sbt = vtop->type.t & VT_BTYPE;
    dbt = ft & VT_BTYPE;
    if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
        (sbt == VT_INT && dbt == VT_SHORT)) {
        /* optimize char/short casts */
        delayed_cast = VT_MUSTCAST;
        vtop->type.t = ft & VT_TYPE;
        /* XXX: factorize */
        if (ft & VT_CONSTANT)
            warning(st, "assignment of read-only location");
    } else {
        delayed_cast = 0;
        if (!(ft & VT_BITFIELD))
            gen_assign_cast(st, &vtop[-1].type);
    }

    if (sbt == VT_STRUCT) {
        /* if structure, only generate pointer */
        /* structure assignment : generate memcpy */
        /* XXX: optimize if small size */
        if (cur_text_section) {
            size = type_size(st, &vtop->type, &align);

#ifdef TCC_ARM_EABI
            if(!(align & 7))
                vpush_global_sym(st, &func_old_type, TOK_memcpy8);
            else if(!(align & 3))
                vpush_global_sym(st, &func_old_type, TOK_memcpy4);
            else
#endif
            vpush_global_sym(st, &func_old_type, TOK_memcpy);

            /* destination */
            vpushv(st, vtop - 2);
            vtop->type.t = VT_INT;
            gaddrof(st);
            /* source */
            vpushv(st, vtop - 2);
            vtop->type.t = VT_INT;
            gaddrof(st);
            /* type size */
            vpushi(st, size);
            gfunc_call(st, 3);
            
            vswap(st);
            vpop(st);
        } else {
            vswap(st);
            vpop(st);
        }
        /* leave source on stack */
    } else if (ft & VT_BITFIELD) {
        /* bitfield store handling */
        bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
        bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
        /* remove bit field info to avoid loops */
        vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));

        /* duplicate source into other register */
        gv_dup(st);
        vswap(st);
        vrott(st, 3);

        /* duplicate destination */
        vdup(st);
        vtop[-1] = vtop[-2];

        /* mask and shift source */
        vpushi(st, (1 << bit_size) - 1);
        gen_op(st, '&');
        vpushi(st, bit_pos);
        gen_op(st, TOK_SHL);
        /* load destination, mask and or with source */
        vswap(st);
        vpushi(st, ~(((1 << bit_size) - 1) << bit_pos));
        gen_op(st, '&');
        gen_op(st, '|');
        /* store result */
        vstore(st);

        /* pop off shifted source from "duplicate source..." above */
        vpop(st);

    } else {
#if 0
        /* bound check case */
        if (vtop[-1].r & VT_MUSTBOUND) {
            vswap(st);
            gbound(st);
            vswap(st);
        }
#endif
        if (cur_text_section) {
            rc = RC_INT;
            if (is_float(st, ft))
                rc = RC_FLOAT;
            r = gv(st, rc);  /* generate value */
            /* if lvalue was saved on stack, must read it */
            if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
                SValue sv;
                t = get_reg(st, RC_INT);
                sv.type.t = VT_INT;
                sv.r = VT_LOCAL | VT_LVAL;
                sv.c.ul = vtop[-1].c.ul;
                load(st, t, &sv);
                vtop[-1].r = t | VT_LVAL;
            }
            store(st, r, vtop - 1);
            /* two word case handling : store second register at word + 4 */
            if ((ft & VT_BTYPE) == VT_LLONG) {
                vswap(st);
                /* convert to int to increment easily */
                vtop->type.t = VT_INT;
                gaddrof(st);
                vpushi(st, 4);
                gen_op(st, '+');
                vtop->r |= VT_LVAL;
                vswap(st);
                /* XXX: it works because r2 is spilled last ! */
                store(st, vtop->r2, vtop - 1);
            }
        }
        vswap(st);
        vtop--; /* NOT vpop(st) because on x86 it would flush the fp stack */
        vtop->r |= delayed_cast;
    }
}

/* post defines POST/PRE add. c is the token ++ or -- */
void inc(TCCState *st, int post, int c)
{
    test_lvalue(st);
    vdup(st); /* save lvalue */
    if (post) {
        gv_dup(st); /* duplicate value */
        vrotb(st, 3);
        vrotb(st, 3);
    }
    /* add constant */
    vpushi(st, c - TOK_MID); 
    gen_op(st, '+');
    vstore(st); /* store value */
    if (post)
        vpop(st); /* if post op, return saved value */
}

/* Parse GNUC __attribute__ extension. Currently, the following
   extensions are recognized:
   - aligned(n) : set data/function alignment.
   - packed : force data alignment to 1
   - section(x) : generate data/code in this section.
   - unused : currently ignored, but may be used someday.
   - regparm(n) : pass function parameters in registers (i386 only)
 */
static void parse_attribute(TCCState *st, AttributeDef *ad)
{
    int t, n;
    
    while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
    next(st);
    skip(st, '(');
    skip(st, '(');
    while (tok != ')') {
        if (tok < TOK_IDENT)
            expect(st, "attribute name");
        t = tok;
        next(st);
        switch(t) {
        case TOK_SECTION1:
        case TOK_SECTION2:
            skip(st, '(');
            if (tok != TOK_STR)
                expect(st, "section name");
            ad->section = find_section(st, (char *)tokc.cstr->data);
            next(st);
            skip(st, ')');
            break;
        case TOK_ALIGNED1:
        case TOK_ALIGNED2:
            if (tok == '(') {
                next(st);
                n = expr_const(st);
                if (n <= 0 || (n & (n - 1)) != 0) 
                   tcc_error(st, "alignment must be a positive power of two");
                skip(st, ')');
            } else {
                n = MAX_ALIGN;
            }
            ad->aligned = n;
            break;
        case TOK_PACKED1:
        case TOK_PACKED2:
            ad->packed = 1;
            break;
        case TOK_UNUSED1:
        case TOK_UNUSED2:
            /* currently, no need to handle it because tcc does not
               track unused objects */
            break;
        case TOK_NORETURN1:
        case TOK_NORETURN2:
            /* currently, no need to handle it because tcc does not
               track unused objects */
            break;
        case TOK_CDECL1:
        case TOK_CDECL2:
        case TOK_CDECL3:
            ad->func_call = FUNC_CDECL;
            break;
        case TOK_STDCALL1:
        case TOK_STDCALL2:
        case TOK_STDCALL3:
            ad->func_call = FUNC_STDCALL;
            break;
#ifdef TCC_TARGET_I386
        case TOK_REGPARM1:
        case TOK_REGPARM2:
            skip(st, '(');
            n = expr_const(st);
            if (n > 3) 
                n = 3;
            else if (n < 0)
                n = 0;
            if (n > 0)
                ad->func_call = FUNC_FASTCALL1 + n - 1;
            skip(st, ')');
            break;
        case TOK_FASTCALL1:
        case TOK_FASTCALL2:
        case TOK_FASTCALL3:
            ad->func_call = FUNC_FASTCALLW;
            break;            
#endif
        case TOK_DLLEXPORT:
            ad->dllexport = 1;
            break;
        default:
            if (st->warn_unsupported)
                warning(st, "'%s' attribute ignored", get_tok_str(st, t, NULL));
            /* skip parameters */
            if (tok == '(') {
                int parenthesis = 0;
                do {
                    if (tok == '(') parenthesis++;
                    else if (tok == ')') parenthesis--;
                    next(st);
                } while (parenthesis && tok != -1);
            }
            break;
        }
        if (tok != ',')
            break;
        next(st);
    }
    skip(st, ')');
    skip(st, ')');
    }
}

/* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
static void struct_decl(TCCState *st, CType *type, int u)
{
    int a, v, size, align, maxalign, c, offset;
    int bit_size, bit_pos, bsize, bt, lbit_pos;
    Sym *s, *ss, *ass, **ps;
    AttributeDef ad;
    CType type1, btype;

    a = tok; /* save decl type */
    next(st);
    if (tok != '{') {
        v = tok;
        next(st);
        /* struct already defined ? return it */
        if (v < TOK_IDENT)
            expect(st, "struct/union/enum name");
        s = struct_find(st, v);
        if (s) {
            if (s->type.t != a)
               tcc_error(st, "invalid type");
            goto do_decl;
        }
    } else {
        v = anon_sym++;
    }
    type1.t = a;
    /* we put an undefined size for struct/union */
    s = sym_push(st, v | SYM_STRUCT, &type1, 0, -1);
    s->r = 0; /* default alignment is zero as gcc */
    /* put struct/union/enum name in type */
 do_decl:
    type->t = u;
    type->ref = s;
    
    if (tok == '{') {
        next(st);
        if (s->c != -1)
           tcc_error(st, "struct/union/enum already defined");
        /* cannot be empty */
        c = 0;
        /* non empty enums are not allowed */
        if (a == TOK_ENUM) {
            for(;;) {
                v = tok;
                if (v < TOK_UIDENT)
                    expect(st, "identifier");
                next(st);
                if (tok == '=') {
                    next(st);
                    c = expr_const(st);
                }
                /* enum symbols have static storage */
                ss = sym_push(st, v, &int_type, VT_CONST, c);
                ss->type.t |= VT_STATIC;
                if (tok != ',')
                    break;
                next(st);
                c++;
                /* NOTE: we accept a trailing comma */
                if (tok == '}')
                    break;
            }
            skip(st, '}');
        } else {
            maxalign = 1;
            ps = &s->next;
            bit_pos = 0;
            offset = 0;
            while (tok != '}') {
                parse_btype(st, &btype, &ad);
                while (1) {
                    bit_size = -1;
                    v = 0;
                    type1 = btype;
                    if (tok != ':') {
                        type_decl(st, &type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
                        if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
                            expect(st, "identifier");
                        if ((type1.t & VT_BTYPE) == VT_FUNC ||
                            (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
                           tcc_error(st, "invalid type for '%s'", 
                                  get_tok_str(st, v, NULL));
                    }
                    if (tok == ':') {
                        next(st);
                        bit_size = expr_const(st);
                        /* XXX: handle v = 0 case for messages */
                        if (bit_size < 0)
                           tcc_error(st, "negative width in bit-field '%s'", 
                                  get_tok_str(st, v, NULL));
                        if (v && bit_size == 0)
                           tcc_error(st, "zero width for bit-field '%s'", 
                                  get_tok_str(st, v, NULL));
                    }
                    size = type_size(st, &type1, &align);
                    if (ad.aligned) {
                        if (align < ad.aligned)
                            align = ad.aligned;
                    } else if (ad.packed) {
                        align = 1;
                    } else if (*st->pack_stack_ptr) {
                        if (align > *st->pack_stack_ptr)
                            align = *st->pack_stack_ptr;
                    }
                    lbit_pos = 0;
                    if (bit_size >= 0) {
                        bt = type1.t & VT_BTYPE;
                        if (bt != VT_INT && 
                            bt != VT_BYTE && 
                            bt != VT_SHORT &&
                            bt != VT_BOOL &&
                            bt != VT_ENUM)
                           tcc_error(st, "bitfields must have scalar type");
                        bsize = size * 8;
                        if (bit_size > bsize) {
                           tcc_error(st, "width of '%s' exceeds its type",
                                  get_tok_str(st, v, NULL));
                        } else if (bit_size == bsize) {
                            /* no need for bit fields */
                            bit_pos = 0;
                        } else if (bit_size == 0) {
                            /* XXX: what to do if only padding in a
                               structure ? */
                            /* zero size: means to pad */
                            if (bit_pos > 0)
                                bit_pos = bsize;
                        } else {
                            /* we do not have enough room ? */
                            if ((bit_pos + bit_size) > bsize)
                                bit_pos = 0;
                            lbit_pos = bit_pos;
                            /* XXX: handle LSB first */
                            type1.t |= VT_BITFIELD | 
                                (bit_pos << VT_STRUCT_SHIFT) |
                                (bit_size << (VT_STRUCT_SHIFT + 6));
                            bit_pos += bit_size;
                        }
                    } else {
                        bit_pos = 0;
                    }
                    if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
                        /* add new memory data only if starting
                           bit field */
                        if (lbit_pos == 0) {
                            if (a == TOK_STRUCT) {
                                c = (c + align - 1) & -align;
                                offset = c;
                                if (size > 0)
                                    c += size;
                            } else {
                                offset = 0;
                                if (size > c)
                                    c = size;
                            }
                            if (align > maxalign)
                                maxalign = align;
                        }
#if 0
                        printf("add field %s offset=%d", 
                               get_tok_str(st, v, NULL), offset);
                        if (type1.t & VT_BITFIELD) {
                            printf(" pos=%d size=%d", 
                                   (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
                                   (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
                        }
                        printf("\n");
#endif
                    }
                    if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
                        ass = type1.ref;
                        while ((ass = ass->next) != NULL) {
                           ss = sym_push(st, ass->v, &ass->type, 0, offset + ass->c);
                           *ps = ss;
                           ps = &ss->next;
                        }
                    } else if (v) {
                        ss = sym_push(st, v | SYM_FIELD, &type1, 0, offset);
                        *ps = ss;
                        ps = &ss->next;
                    }
                    if (tok == ';' || tok == TOK_EOF)
                        break;
                    skip(st, ',');
                }
                skip(st, ';');
            }
            skip(st, '}');
            /* store size and alignment */
            s->c = (c + maxalign - 1) & -maxalign; 
            s->r = maxalign;
        }
    }
}

/* return 0 if no type declaration. otherwise, return the basic type
   and skip it. 
 */
static int parse_btype(TCCState *st, CType *type, AttributeDef *ad)
{
    int t, u, type_found, typespec_found, typedef_found;
    Sym *s;
    CType type1;

    memset(ad, 0, sizeof(AttributeDef));
    type_found = 0;
    typespec_found = 0;
    typedef_found = 0;
    t = 0;
    while(1) {
        switch(tok) {
        case TOK_EXTENSION:
            /* currently, we really ignore extension */
            next(st);
            continue;

            /* basic types */
        case TOK_CHAR:
            u = VT_BYTE;
        basic_type:
            next(st);
        basic_type1:
            if ((t & VT_BTYPE) != 0)
               tcc_error(st, "too many basic types");
            t |= u;
            typespec_found = 1;
            break;
        case TOK_VOID:
            u = VT_VOID;
            goto basic_type;
        case TOK_SHORT:
            u = VT_SHORT;
            goto basic_type;
        case TOK_INT:
            next(st);
            typespec_found = 1;
            break;
        case TOK_LONG:
            next(st);
            if ((t & VT_BTYPE) == VT_DOUBLE) {
                t = (t & ~VT_BTYPE) | VT_LDOUBLE;
            } else if ((t & VT_BTYPE) == VT_LONG) {
                t = (t & ~VT_BTYPE) | VT_LLONG;
            } else {
                u = VT_LONG;
                goto basic_type1;
            }
            break;
        case TOK_BOOL:
            u = VT_BOOL;
            goto basic_type;
        case TOK_FLOAT:
            u = VT_FLOAT;
            goto basic_type;
        case TOK_DOUBLE:
            next(st);
            if ((t & VT_BTYPE) == VT_LONG) {
                t = (t & ~VT_BTYPE) | VT_LDOUBLE;
            } else {
                u = VT_DOUBLE;
                goto basic_type1;
            }
            break;
        case TOK_ENUM:
            struct_decl(st, &type1, VT_ENUM);
        basic_type2:
            u = type1.t;
            type->ref = type1.ref;
            goto basic_type1;
        case TOK_STRUCT:
        case TOK_UNION:
            struct_decl(st, &type1, VT_STRUCT);
            goto basic_type2;

            /* type modifiers */
        case TOK_CONST1:
        case TOK_CONST2:
        case TOK_CONST3:
            t |= VT_CONSTANT;
            next(st);
            break;
        case TOK_VOLATILE1:
        case TOK_VOLATILE2:
        case TOK_VOLATILE3:
            t |= VT_VOLATILE;
            next(st);
            break;
        case TOK_SIGNED1:
        case TOK_SIGNED2:
        case TOK_SIGNED3:
            typespec_found = 1;
            t |= VT_SIGNED;
            next(st);
            break;
        case TOK_REGISTER:
        case TOK_AUTO:
        case TOK_RESTRICT1:
        case TOK_RESTRICT2:
        case TOK_RESTRICT3:
            next(st);
            break;
        case TOK_UNSIGNED:
            t |= VT_UNSIGNED;
            next(st);
            typespec_found = 1;
            break;

            /* storage */
        case TOK_EXTERN:
            t |= VT_EXTERN;
            next(st);
            break;
        case TOK_STATIC:
            t |= VT_STATIC;
            next(st);
            break;
        case TOK_TYPEDEF:
            t |= VT_TYPEDEF;
            next(st);
            break;
        case TOK_INLINE1:
        case TOK_INLINE2:
        case TOK_INLINE3:
            t |= VT_INLINE;
            next(st);
            break;

            /* GNUC attribute */
        case TOK_ATTRIBUTE1:
        case TOK_ATTRIBUTE2:
            parse_attribute(st, ad);
            break;
            /* GNUC typeof */
        case TOK_TYPEOF1:
        case TOK_TYPEOF2:
        case TOK_TYPEOF3:
            next(st);
            parse_expr_type(st, &type1);
            goto basic_type2;
        default:
            if (typespec_found || typedef_found)
                goto the_end;
            s = sym_find(st, tok);
            if (!s || !(s->type.t & VT_TYPEDEF))
                goto the_end;
            typedef_found = 1;
            t |= (s->type.t & ~VT_TYPEDEF);
            type->ref = s->type.ref;
            next(st);
            typespec_found = 1;
            break;
        }
        type_found = 1;
    }
the_end:
    if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
     tcc_error(st, "signed and unsigned modifier");
    if (st->char_is_unsigned) {
        if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
            t |= VT_UNSIGNED;
    }
    t &= ~VT_SIGNED;

    /* long is never used as type */
    if ((t & VT_BTYPE) == VT_LONG)
        t = (t & ~VT_BTYPE) | VT_INT;
    type->t = t;
    return type_found;
}

/* convert a function parameter type (array to pointer and function to
   function pointer) */
static inline void convert_parameter_type(TCCState *st, CType *pt)
{
    /* remove const and volatile qualifiers (XXX: const could be used
       to indicate a const function parameter */
    pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
    /* array must be transformed to pointer according to ANSI C */
    pt->t &= ~VT_ARRAY;
    if ((pt->t & VT_BTYPE) == VT_FUNC) {
        mk_pointer(st, pt);
    }
}

static void parse_function_parameters(TCCState *st, CType *type, AttributeDef *ad)
{
    int n, l, t1;
    Sym **plast, *s, *first;
    AttributeDef ad1;
    CType pt;

    /* Starting with '(' parse attributes for function declaration */
    next(st);
    l = 0;
    first = NULL;
    plast = &first;
    if (tok != ')') {
        for(;;) {
            /* read param name and compute offset */
            if (l != FUNC_OLD) {
                if (!parse_btype(st, &pt, &ad1)) {
                    if (l) {
                       tcc_error(st, "invalid type");
                    } else {
                        l = FUNC_OLD;
                        goto old_proto;
                    }
                }
                l = FUNC_NEW;
                if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
                    break;
                type_decl(st, &pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
                if ((pt.t & VT_BTYPE) == VT_VOID)
                   tcc_error(st, "parameter declared as void");
            } else {
            old_proto:
                n = tok;
                if (n < TOK_UIDENT)
                    expect(st, "identifier");
                pt.t = VT_INT;
                next(st);
            }
            convert_parameter_type(st, &pt);
            s = sym_push(st, n | SYM_FIELD, &pt, 0, 0);
            *plast = s;
            plast = &s->next;
            if (tok == ')')
                break;
            skip(st, ',');
            if (l == FUNC_NEW && tok == TOK_DOTS) {
                l = FUNC_ELLIPSIS;
                next(st);
                break;
            }
        }
    }
    /* if no parameters, then old type prototype */
    if (!l) l = FUNC_OLD;
    skip(st, ')');
    t1 = type->t & VT_STORAGE;
    /* NOTE: const is ignored in returned type as it has a special
       meaning in gcc / C++ */
    type->t &= ~(VT_STORAGE | VT_CONSTANT); 
    /* we push a anonymous symbol which will contain the function prototype */
    s = sym_push(st, SYM_FIELD, type, ad->func_call, l);
    s->next = first;
    type->t = t1 | VT_FUNC;
    type->ref = s;
}

static void parse_array_dimensions(TCCState *st, CType *type)
{
    int n = -1, t1;
    Sym *s;

    /* Starting with '[' parse array dimensions */
    next(st);
    if (tok == TOK_RESTRICT1) next(st); 
    if (tok != ']') {
        char *message = "invalid array size";
        expr_const1(st);
        /* Conventional constant array? */
        if ((vtop->r & (VT_VALMASK |VT_LVAL | VT_SYM)) == VT_CONST) {
            n = vtop->c.i;
            vpop(st);

            if (n < 0)tcc_error(st, message);
        } else if (!local_stack)tcc_error(st, message);
        else {
            gen_assign_cast(st, &int_type);
            n = -2;
           tcc_error(st, "dynamic arrays not implemented yet");
        }
    }
    skip(st, ']');
    /* parse next post type */
    t1 = type->t & VT_STORAGE;
    type->t &= ~VT_STORAGE;
    if (tok == '[') parse_array_dimensions(st, type);
    
    /* we push a anonymous symbol which will contain the array
       element type */
    s = sym_push(st, SYM_FIELD, type, 0, n);
    type->t = t1 | VT_ARRAY | VT_PTR;
    type->ref = s;
}

/* Parse a type declaration (except basic type), and return the type
   in 'type'. 'td' is a bitmask indicating which kind of type decl is
   expected. 'type' should contain the basic type. 'ad' is the
   attribute definition of the basic type. It can be modified by
   type_decl(st). 
 */
static void type_decl(TCCState *st, CType *type, AttributeDef *ad, int *v, int td)
{
    Sym *s;
    CType type1, *type2;
    int qualifiers;
    
    while (tok == '*') {
        qualifiers = 0;
    redo:
        next(st);
        switch(tok) {
        case TOK_CONST1:
        case TOK_CONST2:
        case TOK_CONST3:
            qualifiers |= VT_CONSTANT;
            goto redo;
        case TOK_VOLATILE1:
        case TOK_VOLATILE2:
        case TOK_VOLATILE3:
            qualifiers |= VT_VOLATILE;
            goto redo;
        case TOK_RESTRICT1:
        case TOK_RESTRICT2:
        case TOK_RESTRICT3:
            goto redo;
        }
        mk_pointer(st, type);
        type->t |= qualifiers;
    }
    
    /* XXX: clarify attribute handling */
    if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
        parse_attribute(st, ad);

    /* recursive type */
    /* XXX: incorrect if abstract type for functions (e.g. 'int (st)') */
    type1.t = 0; /* XXX: same as int */
    if (tok == '(') {
        next(st);
        /* XXX: this is not correct to modify 'ad' at this point, but
           the syntax is not clear */
        if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
            parse_attribute(st, ad);
        type_decl(st, &type1, ad, v, td);
        skip(st, ')');
    } else {
        /* type identifier */
        if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
            *v = tok;
            next(st);
        } else {
            if (!(td & TYPE_ABSTRACT))
                expect(st, "identifier");
            *v = 0;
        }
    }
    if (tok == '(') parse_function_parameters(st, type, ad);
    else if (tok == '[') parse_array_dimensions(st, type);
    if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
        parse_attribute(st, ad);
    if (!type1.t)
        return;
    /* append type at the end of type1 */
    type2 = &type1;
    for(;;) {
        s = type2->ref;
        type2 = &s->type;
        if (!type2->t) {
            *type2 = *type;
            break;
        }
    }
    *type = type1;
}

/* compute the lvalue VT_LVAL_xxx needed to match type t. */
static int lvalue_type(TCCState *st, int t)
{
    int bt, r;
    r = VT_LVAL;
    bt = t & VT_BTYPE;
    if (bt == VT_BYTE || bt == VT_BOOL)
        r |= VT_LVAL_BYTE;
    else if (bt == VT_SHORT)
        r |= VT_LVAL_SHORT;
    else
        return r;
    if (t & VT_UNSIGNED)
        r |= VT_LVAL_UNSIGNED;
    return r;
}

/* indirection with full error checking and bound check */
static void indir(TCCState *st)
{
    if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
        if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
            return;
        expect(st, "pointer");
    }
    if ((vtop->r & VT_LVAL) && cur_text_section)
        gv(st, RC_INT);
    vtop->type = *pointed_type(st, &vtop->type);
    /* Arrays and functions are never lvalues */
    if (!(vtop->type.t & VT_ARRAY)
        && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
        vtop->r |= lvalue_type(st, vtop->type.t);
        /* if bound checking, the referenced pointer must be checked */
        if (do_bounds_check) 
            vtop->r |= VT_MUSTBOUND;
    }
}

/* pass a parameter to a function and do type checking and casting */
static void gfunc_param_typed(TCCState *st, Sym *func, Sym *arg)
{
    int func_type;
    CType type;

    func_type = func->c;
    if (func_type == FUNC_OLD ||
        (func_type == FUNC_ELLIPSIS && arg == NULL)) {
        /* default casting : only need to convert float to double */
        if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
            type.t = VT_DOUBLE;
            gen_cast(st, &type);
        }
    } else if (arg == NULL) {
       tcc_error(st, "too many arguments to function");
    } else {
        type = arg->type;
        type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
        gen_assign_cast(st, &type);
    }
}

/* parse an expression of the form '(type)' or '(expr)' and return its
   type */
static void parse_expr_type(TCCState *st, CType *type)
{
    int n;
    AttributeDef ad;

    skip(st, '(');
    if (parse_btype(st, type, &ad)) {
        type_decl(st, type, &ad, &n, TYPE_ABSTRACT);
    } else {
        expr_type(st, type);
    }
    skip(st, ')');
}

static void parse_type(TCCState *st, CType *type)
{
    AttributeDef ad;
    int n;

    if (!parse_btype(st, type, &ad)) {
        expect(st, "type");
    }
    type_decl(st, type, &ad, &n, TYPE_ABSTRACT);
}

static void vpush_tokc(TCCState *st, int t)
{
    CType type;
    type.t = t;
    vsetc(st, &type, VT_CONST, &tokc);
}

static void unary(TCCState *st)
{
    int n, t, align, size, r;
    CType type;
    Sym *s;
    AttributeDef ad;

    /* XXX: GCC 2.95.3 does not generate a table although it should be
       better here */
 tok_next:
    switch(tok) {
    case TOK_EXTENSION:
        next(st);
        goto tok_next;
    case TOK_CINT:
    case TOK_CCHAR: 
    case TOK_LCHAR:
        vpushi(st, tokc.i);
        next(st);
        break;
    case TOK_CUINT:
        vpush_tokc(st, VT_INT | VT_UNSIGNED);
        next(st);
        break;
    case TOK_CLLONG:
        vpush_tokc(st, VT_LLONG);
        next(st);
        break;
    case TOK_CULLONG:
        vpush_tokc(st, VT_LLONG | VT_UNSIGNED);
        next(st);
        break;
    case TOK_CFLOAT:
        vpush_tokc(st, VT_FLOAT);
        next(st);
        break;
    case TOK_CDOUBLE:
        vpush_tokc(st, VT_DOUBLE);
        next(st);
        break;
    case TOK_CLDOUBLE:
        vpush_tokc(st, VT_LDOUBLE);
        next(st);
        break;
    case TOK___FUNCTION__:
        if (!gnu_ext)
            goto tok_identifier;
        /* fall thru */
    case TOK___FUNC__:
        {
            void *ptr;
            int len;
            /* special function name identifier */
            len = strlen(funcname) + 1;
            /* generate char[len] type */
            type.t = VT_BYTE;
            mk_pointer(st, &type);
            type.t |= VT_ARRAY;
            type.ref->c = len;
            vpush_ref(st, &type, data_section, data_section->data_offset, len);
            ptr = section_ptr_add(st, data_section, len);
            memcpy(ptr, funcname, len);
            next(st);
        }
        break;
    case TOK_LSTR:
#ifdef WIN32
        t = VT_SHORT | VT_UNSIGNED;
#else
        t = VT_INT;
#endif
        goto str_init;
    case TOK_STR:
        /* string parsing */
        t = VT_BYTE;
    str_init:
        if (st->warn_write_strings)
            t |= VT_CONSTANT;
        type.t = t;
        mk_pointer(st, &type);
        type.t |= VT_ARRAY;
        memset(&ad, 0, sizeof(AttributeDef));
        decl_initializer_alloc(st, &type, &ad, VT_CONST, 2, 0, 0);
        break;
    case '(':
        next(st);
        /* cast ? */
        if (parse_btype(st, &type, &ad)) {
            type_decl(st, &type, &ad, &n, TYPE_ABSTRACT);
            skip(st, ')');
            /* check ISOC99 compound literal */
            if (tok == '{') {
                    /* data is allocated locally by default */
                if (global_expr)
                    r = VT_CONST;
                else
                    r = VT_LOCAL;
                /* all except arrays are lvalues */
                if (!(type.t & VT_ARRAY))
                    r |= lvalue_type(st, type.t);
                memset(&ad, 0, sizeof(AttributeDef));
                decl_initializer_alloc(st, &type, &ad, r, 1, 0, 0);
            } else {
                unary(st);
                gen_cast(st, &type);
            }
        } else if (tok == '{') {
            /* save all registers */
            save_regs(st, 0); 
            /* statement expression : we do not accept break/continue
               inside as GCC does */
            block(st, NULL, NULL, NULL, NULL, 0, 1);
            skip(st, ')');
        } else {
            gexpr(st);
            skip(st, ')');
        }
        break;
    case '*':
        next(st);
        unary(st);
        indir(st);
        break;
    case '&':
        next(st);
        unary(st);
        /* functions names must be treated as function pointers,
           except for unary '&' and sizeof. Since we consider that
           functions are not lvalues, we only have to handle it
           there and in function calls. */
        /* arrays can also be used although they are not lvalues */
        if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
            !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
            test_lvalue(st);
        mk_pointer(st, &vtop->type);
        gaddrof(st);
        break;
    case '!':
        next(st);
        unary(st);
        if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST)
            vtop->c.i = !vtop->c.i;
        else if ((vtop->r & VT_VALMASK) == VT_CMP)
            vtop->c.i = vtop->c.i ^ 1;
        else {
            save_regs(st, 1);
            vseti(st, VT_JMP, gtst(st, 1, 0));
        }
        break;
    case '~':
        next(st);
        unary(st);
        vpushi(st, -1);
        gen_op(st, '^');
        break;
    case '+':
        next(st);
        /* in order to force cast, we add zero */
        unary(st);
        if ((vtop->type.t & VT_BTYPE) == VT_PTR)
           tcc_error(st, "pointer not accepted for unary plus");
        vpushi(st, 0);
        gen_op(st, '+');
        break;
    case TOK_SIZEOF:
    case TOK_ALIGNOF1:
    case TOK_ALIGNOF2:
        t = tok;
        next(st);
        if (tok == '(') {
            parse_expr_type(st, &type);
        } else {
            unary_type(st, &type);
        }
        size = type_size(st, &type, &align);
        if (t == TOK_SIZEOF) {
            if (size < 0)
               tcc_error(st, "sizeof applied to an incomplete type");
            vpushi(st, size);
        } else {
            vpushi(st, align);
        }
        vtop->type.t |= VT_UNSIGNED;
        break;

    case TOK_builtin_types_compatible_p:
        {
            CType type1, type2;
            next(st);
            skip(st, '(');
            parse_type(st, &type1);
            skip(st, ',');
            parse_type(st, &type2);
            skip(st, ')');
            type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
            type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
            vpushi(st, is_compatible_types(st, &type1, &type2));
        }
        break;
    case TOK_builtin_constant_p:
        {
            Section *saved_text_section;
            int res;
            next(st);
            skip(st, '(');
            saved_text_section = cur_text_section;
            cur_text_section = NULL;
            gexpr(st);
            res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
            vpop(st);
            cur_text_section = saved_text_section;
            skip(st, ')');
            vpushi(st, res);
        }
        break;
    case TOK_INC:
    case TOK_DEC:
        t = tok;
        next(st);
        unary(st);
        inc(st, 0, t);
        break;
    case '-':
        next(st);
        vpushi(st, 0);
        unary(st);
        gen_op(st, '-');
        break;
    case TOK_LAND:
        if (!gnu_ext)
            goto tok_identifier;
        next(st);
        /* allow to take the address of a label */
        if (tok < TOK_UIDENT)
            expect(st, "label identifier");
        s = label_find(st, tok);
        if (!s) {
            s = label_push(st, &global_label_stack, tok, LABEL_FORWARD);
        } else {
            if (s->r == LABEL_DECLARED)
                s->r = LABEL_FORWARD;
        }
        if (!s->type.t) {
            s->type.t = VT_VOID;
            mk_pointer(st, &s->type);
            s->type.t |= VT_STATIC;
        }
        vset(st, &s->type, VT_CONST | VT_SYM, 0);
        vtop->sym = s;
        next(st);
        break;
    default:
    tok_identifier:
        t = tok;
        next(st);
        if (t < TOK_UIDENT)
            expect(st, "identifier");
        s = sym_find(st, t);
        if (!s) {
            if (tok != '(')
               tcc_error(st, "'%s' undeclared", get_tok_str(st, t, NULL));
            /* for simple function calls, we tolerate undeclared
               external reference to int(st) function */
            if (st->warn_implicit_function_declaration)
                warning(st, "implicit declaration of function '%s'",
                        get_tok_str(st, t, NULL));
            s = external_global_sym(st, t, &func_old_type, 0); 
        }
        if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
            (VT_STATIC | VT_INLINE | VT_FUNC)) {
            /* if referencing an inline function, then we generate a
               symbol to it if not already done. It will have the
               effect to generate code for it at the end of the
               compilation unit. Inline function as always
               generated in the text section. */
            if (!s->c)
                put_extern_sym(st, s, text_section, 0, 0);
            r = VT_SYM | VT_CONST;
        } else {
            r = s->r;
        }
        vset(st, &s->type, r, s->c);
        /* if forward reference, we must point to s */
        if (vtop->r & VT_SYM) {
            vtop->sym = s;
            vtop->c.ul = 0;
        }
        break;
    }
    
    /* post operations */
    while (1) {
        if (tok == TOK_INC || tok == TOK_DEC) {
            inc(st, 1, tok);
            next(st);
        } else if (tok == '.' || tok == TOK_ARROW) {
            /* field */ 
            if (tok == TOK_ARROW) 
                indir(st);
            test_lvalue(st);
            gaddrof(st);
            next(st);
            /* expect pointer on structure */
            if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
                expect(st, "struct or union");
            s = vtop->type.ref;
            /* find field */
            tok |= SYM_FIELD;
            while ((s = s->next) != NULL) {
                if (s->v == tok)
                    break;
            }
            if (!s)
               tcc_error(st, "field not found");
            /* add field offset to pointer */
            vtop->type = char_pointer_type; /* change type to 'char *' */
            vpushi(st, s->c);
            gen_op(st, '+');
            /* change type to field type, and set to lvalue */
            vtop->type = s->type;
            /* an array is never an lvalue */
            if (!(vtop->type.t & VT_ARRAY)) {
                vtop->r |= lvalue_type(st, vtop->type.t);
                /* if bound checking, the referenced pointer must be checked */
                if (do_bounds_check) 
                    vtop->r |= VT_MUSTBOUND;
            }
            next(st);
        } else if (tok == '[') {
            next(st);
            gexpr(st);
            gen_op(st, '+');
            indir(st);
            skip(st, ']');
        } else if (tok == '(') {
            SValue ret;
            Sym *sa;
            int nb_args;

            /* function call  */
            if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
                /* pointer test (no array accepted) */
                if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
                    vtop->type = *pointed_type(st, &vtop->type);
                    if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
                        goto error_func;
                } else {
                error_func:
                    expect(st, "function pointer");
                }
            } else {
                vtop->r &= ~VT_LVAL; /* no lvalue */
            }
            /* get return type */
            s = vtop->type.ref;
            next(st);
            sa = s->next; /* first parameter */
            nb_args = 0;
            /* compute first implicit argument if a structure is returned */
            if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
                /* get some space for the returned structure */
                size = type_size(st, &s->type, &align);
                loc = (loc - size) & -align;
                ret.type = s->type;
                ret.r = VT_LOCAL | VT_LVAL;
                /* pass it as 'int' to avoid structure arg passing
                   problems */
                vseti(st, VT_LOCAL, loc);
                ret.c = vtop->c;
                nb_args++;
            } else {
                ret.type = s->type; 
                ret.r2 = VT_CONST;
                /* return in register */
                if (is_float(st, ret.type.t)) {
                    ret.r = REG_FRET; 
                } else {
                    if ((ret.type.t & VT_BTYPE) == VT_LLONG)
                        ret.r2 = REG_LRET;
                    ret.r = REG_IRET;
                }
                ret.c.i = 0;
            }
            if (tok != ')') {
                for(;;) {
                    expr_eq(st);
                    gfunc_param_typed(st, s, sa);
                    nb_args++;
                    if (sa)
                        sa = sa->next;
                    if (tok == ')')
                        break;
                    skip(st, ',');
                }
            }
            if (sa)
               tcc_error(st, "too few arguments to function");
            skip(st, ')');
            if (cur_text_section) gfunc_call(st, nb_args);
            else vtop -= (nb_args + 1);
            /* return value */
            vsetc(st, &ret.type, ret.r, &ret.c);
            vtop->r2 = ret.r2;
        } else {
            break;
        }
    }
}

static void uneq(TCCState *st)
{
    int t;
    
    unary(st);
    if (tok == '=' ||
        (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
        tok == TOK_A_XOR || tok == TOK_A_OR ||
        tok == TOK_A_SHL || tok == TOK_A_SAR) {
        test_lvalue(st);
        t = tok;
        next(st);
        if (t == '=') {
            expr_eq(st);
        } else {
            vdup(st);
            expr_eq(st);
            gen_op(st, t & 0x7f);
        }
        vstore(st);
    }
}

static void expr_prod(TCCState *st)
{
    int t;

    uneq(st);
    while (tok == '*' || tok == '/' || tok == '%') {
        t = tok;
        next(st);
        uneq(st);
        gen_op(st, t);
    }
}

static void expr_sum(TCCState *st)
{
    int t;

    expr_prod(st);
    while (tok == '+' || tok == '-') {
        t = tok;
        next(st);
        expr_prod(st);
        gen_op(st, t);
    }
}

static void expr_shift(TCCState *st)
{
    int t;

    expr_sum(st);
    while (tok == TOK_SHL || tok == TOK_SAR) {
        t = tok;
        next(st);
        expr_sum(st);
        gen_op(st, t);
    }
}

static void expr_cmp(TCCState *st)
{
    int t;

    expr_shift(st);
    while ((tok >= TOK_ULE && tok <= TOK_GT) ||
           tok == TOK_ULT || tok == TOK_UGE) {
        t = tok;
        next(st);
        expr_shift(st);
        gen_op(st, t);
    }
}

static void expr_cmpeq(TCCState *st)
{
    int t;

    expr_cmp(st);
    while (tok == TOK_EQ || tok == TOK_NE) {
        t = tok;
        next(st);
        expr_cmp(st);
        gen_op(st, t);
    }
}

static void expr_and(TCCState *st)
{
    expr_cmpeq(st);
    while (tok == '&') {
        next(st);
        expr_cmpeq(st);
        gen_op(st, '&');
    }
}

static void expr_xor(TCCState *st)
{
    expr_and(st);
    while (tok == '^') {
        next(st);
        expr_and(st);
        gen_op(st, '^');
    }
}

static void expr_or(TCCState *st)
{
    expr_xor(st);
    while (tok == '|') {
        next(st);
        expr_xor(st);
        gen_op(st, '|');
    }
}

/* XXX: fix this mess */
static void expr_land_const(TCCState *st)
{
    expr_or(st);
    while (tok == TOK_LAND) {
        next(st);
        expr_or(st);
        gen_op(st, TOK_LAND);
    }
}

/* XXX: fix this mess */
static void expr_lor_const(TCCState *st)
{
    expr_land_const(st);
    while (tok == TOK_LOR) {
        next(st);
        expr_land_const(st);
        gen_op(st, TOK_LOR);
    }
}

/* only used if non constant */
static void expr_land(TCCState *st)
{
    int t;

    expr_or(st);
    if (tok == TOK_LAND) {
        t = 0;
        save_regs(st, 1);
        for(;;) {
            t = gtst(st, 1, t);
            if (tok != TOK_LAND) {
                vseti(st, VT_JMPI, t);
                break;
            }
            next(st);
            expr_or(st);
        }
    }
}

static void expr_lor(TCCState *st)
{
    int t;

    expr_land(st);
    if (tok == TOK_LOR) {
        t = 0;
        save_regs(st, 1);
        for(;;) {
            t = gtst(st, 0, t);
            if (tok != TOK_LOR) {
                vseti(st, VT_JMP, t);
                break;
            }
            next(st);
            expr_land(st);
        }
    }
}

/* XXX: better constant handling */
static void expr_eq(TCCState *st)
{
    int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
    SValue sv;
    CType type, type1, type2;

    if (const_wanted) {
        int c1, c;
        expr_lor_const(st);
        if (tok == '?') {
            c = vtop->c.i;
            vpop(st);
            next(st);
            if (tok == ':' && gnu_ext) {
                c1 = c;
            } else {
                gexpr(st);
                c1 = vtop->c.i;
                vpop(st);
            }
            skip(st, ':');
            expr_eq(st);
            if (c)
                vtop->c.i = c1;
        }
    } else {
        expr_lor(st);
        if (tok == '?') {
            next(st);
            if (vtop != vstack) {
                /* needed to avoid having different registers saved in
                   each branch */
                if (is_float(st, vtop->type.t))
                    rc = RC_FLOAT;
                else
                    rc = RC_INT;
                    gv(st, rc);
                    save_regs(st, 1);
            }
            if (tok == ':' && gnu_ext) {
                gv_dup(st);
                tt = gtst(st, 1, 0);
            } else {
                tt = gtst(st, 1, 0);
                gexpr(st);
            }
            type1 = vtop->type;
            sv = *vtop; /* save value to handle it later */
            vtop--; /* no vpop so that FP stack is not flushed */
            skip(st, ':');
            u = gjmp(st, 0);
            gsym(tt);
            expr_eq(st);
            type2 = vtop->type;

            t1 = type1.t;
            bt1 = t1 & VT_BTYPE;
            t2 = type2.t;
            bt2 = t2 & VT_BTYPE;
            /* cast operands to correct type according to ISOC rules */
            if (is_float(st, bt1) || is_float(st, bt2)) {
                if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
                    type.t = VT_LDOUBLE;
                } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
                    type.t = VT_DOUBLE;
                } else {
                    type.t = VT_FLOAT;
                }
            } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
                /* cast to biggest op */
                type.t = VT_LLONG;
                /* convert to unsigned if it does not fit in a long long */
                if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
                    (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
                    type.t |= VT_UNSIGNED;
            } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
                /* XXX: test pointer compatibility */
                type = type1;
            } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
                /* XXX: test function pointer compatibility */
                type = type1;
            } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
                /* XXX: test structure compatibility */
                type = type1;
            } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
                /* NOTE: as an extension, we accept void on only one side */
                type.t = VT_VOID;
            } else {
                /* integer operations */
                type.t = VT_INT;
                /* convert to unsigned if it does not fit in an integer */
                if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
                    (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
                    type.t |= VT_UNSIGNED;
            }
                
            /* now we convert second operand */
            gen_cast(st, &type);
            if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
                gaddrof(st);
            rc = RC_INT;
            if (is_float(st, type.t)) {
                rc = RC_FLOAT;
            } else if ((type.t & VT_BTYPE) == VT_LLONG) {
                /* for long longs, we use fixed registers to avoid having
                   to handle a complicated move */
                rc = RC_IRET; 
            }
            
            r2 = gv(st, rc);
            /* this is horrible, but we must also convert first
               operand */
            tt = gjmp(st, 0);
            gsym(u);
            /* put again first value and cast it */
            *vtop = sv;
            gen_cast(st, &type);
            if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
                gaddrof(st);
            r1 = gv(st, rc);
            move_reg(st, r2, r1);
            vtop->r = r2;
            gsym(tt);
        }
    }
}

static void gexpr(TCCState *st)
{
    while (1) {
        expr_eq(st);
        if (tok != ',')
            break;
        vpop(st);
        next(st);
    }
}

/* parse an expression and return its type without any side effect. */
static void expr_type(TCCState *st, CType *type)
{
    Section *saved_text_section = cur_text_section;

    cur_text_section = NULL;
    gexpr(st);
    *type = vtop->type;
    vpop(st);
    cur_text_section = saved_text_section;
}

/* parse a unary expression and return its type without any side
   effect. */
static void unary_type(TCCState *st, CType *type)
{
    Section *saved_text_section = cur_text_section;

    cur_text_section = NULL;
    unary(st);
    *type = vtop->type;
    vpop(st);
    cur_text_section = saved_text_section;
}

/* parse a constant expression and return value in vtop.  */
static void expr_const1(TCCState *st)
{
    int a;
    a = const_wanted;
    const_wanted = 1;
    expr_eq(st);
    const_wanted = a;
}

/* parse an integer constant and return its value. */
static int expr_const(TCCState *st)
{
    int c;
    expr_const1(st);
    if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
        expect(st, "constant expression");
    c = vtop->c.i;
    vpop(st);
    return c;
}

/* return the label token if current token is a label, otherwise
   return zero */
static int is_label(TCCState *st)
{
    int last_tok;

    /* fast test first */
    if (tok < TOK_UIDENT)
        return 0;
    /* no need to save tokc because tok is an identifier */
    last_tok = tok;
    next(st);
    if (tok == ':') {
        next(st);
        return last_tok;
    } else {
        unget_tok(st, last_tok);
        return 0;
    }
}

static void block(TCCState *st, int *bsym, int *csym, int *case_sym, int *def_sym, 
                  int case_reg, int is_expr)
{
    int a, b, c, d;
    Sym *s;

    /* generate line number info */
    if (do_debug && 
        (last_line_num != file->line_num || last_ind != ind)) {
        put_stabn(st, N_SLINE, 0, file->line_num, ind - func_ind);
        last_ind = ind;
        last_line_num = file->line_num;
    }

    if (is_expr) {
        /* default return value is (void) */
        vpushi(st, 0);
        vtop->type.t = VT_VOID;
    }

    if (tok == TOK_IF) {
        /* if test */
        next(st);
        skip(st, '(');
        gexpr(st);
        skip(st, ')');
        a = gtst(st, 1, 0);
        block(st, bsym, csym, case_sym, def_sym, case_reg, 0);
        c = tok;
        if (c == TOK_ELSE) {
            next(st);
            d = gjmp(st, 0);
            gsym(a);
            block(st, bsym, csym, case_sym, def_sym, case_reg, 0);
            gsym(d); /* patch else jmp */
        } else
            gsym(a);
    } else if (tok == TOK_WHILE) {
        next(st);
        d = ind;
        skip(st, '(');
        gexpr(st);
        skip(st, ')');
        a = gtst(st, 1, 0);
        b = 0;
        block(st, &a, &b, case_sym, def_sym, case_reg, 0);
        gjmp_addr(st, d);
        gsym(a);
        gsym_addr(b, d);
    } else if (tok == '{') {
        Sym *llabel;
        
        next(st);
        /* record local declaration stack position */
        s = local_stack;
        llabel = local_label_stack;
        /* handle local labels declarations */
        if (tok == TOK_LABEL) {
            next(st);
            for(;;) {
                if (tok < TOK_UIDENT)
                    expect(st, "label identifier");
                label_push(st, &local_label_stack, tok, LABEL_DECLARED);
                next(st);
                if (tok == ',') {
                    next(st);
                } else {
                    skip(st, ';');
                    break;
                }
            }
        }
        while (tok != '}') {
            decl(st, VT_LOCAL);
            if (tok != '}') {
                if (is_expr)
                    vpop(st);
                block(st, bsym, csym, case_sym, def_sym, case_reg, is_expr);
            }
        }
        /* pop locally defined labels */
        label_pop(st, &local_label_stack, llabel);
        /* pop locally defined symbols */
        sym_pop(st, &local_stack, s);
        next(st);
    } else if (tok == TOK_RETURN) {
        next(st);
        if (tok != ';') {
            gexpr(st);
            gen_assign_cast(st, &func_vt);
            if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
                CType type;
                /* if returning structure, must copy it to implicit
                   first pointer arg location */
#ifdef TCC_ARM_EABI
                int align, size;
                size = type_size(st, &func_vt,&align);
                if(size <= 4) {
                    if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
                       && (align & 3))
                    {
                        int addr;
                        loc = (loc - size) & -4;
                        addr = loc;
                        type = func_vt;
                        vset(st, &type, VT_LOCAL | VT_LVAL, addr);
                        vswap(st);
                        vstore(st);
                        vset(st, &int_type, VT_LOCAL | VT_LVAL, addr);
                    }
                    vtop->type = int_type;
                    gv(st, RC_IRET);
                } else {
#endif
                type = func_vt;
                mk_pointer(st, &type);
                vset(st, &type, VT_LOCAL | VT_LVAL, func_vc);
                indir(st);
                vswap(st);
                /* copy structure value to pointer */
                vstore(st);
#ifdef TCC_ARM_EABI
                }
#endif
            } else if (is_float(st, func_vt.t)) {
                gv(st, RC_FRET);
            } else {
                gv(st, RC_IRET);
            }
            vtop--; /* NOT vpop(st) because on x86 it would flush the fp stack */
        }
        skip(st, ';');
        rsym = gjmp(st, rsym); /* jmp */
    } else if (tok == TOK_BREAK) {
        /* compute jump */
        if (!bsym)
           tcc_error(st, "cannot break");
        *bsym = gjmp(st, *bsym);
        next(st);
        skip(st, ';');
    } else if (tok == TOK_CONTINUE) {
        /* compute jump */
        if (!csym)
           tcc_error(st, "cannot continue");
        *csym = gjmp(st, *csym);
        next(st);
        skip(st, ';');
    } else if (tok == TOK_FOR) {
        int e;
        next(st);
        skip(st, '(');
        if (tok != ';') {
            gexpr(st);
            vpop(st);
        }
        skip(st, ';');
        d = ind;
        c = ind;
        a = 0;
        b = 0;
        if (tok != ';') {
            gexpr(st);
            a = gtst(st, 1, 0);
        }
        skip(st, ';');
        if (tok != ')') {
            e = gjmp(st, 0);
            c = ind;
            gexpr(st);
            vpop(st);
            gjmp_addr(st, d);
            gsym(e);
        }
        skip(st, ')');
        block(st, &a, &b, case_sym, def_sym, case_reg, 0);
        gjmp_addr(st, c);
        gsym(a);
        gsym_addr(b, c);
    } else 
    if (tok == TOK_DO) {
        next(st);
        a = 0;
        b = 0;
        d = ind;
        block(st, &a, &b, case_sym, def_sym, case_reg, 0);
        skip(st, TOK_WHILE);
        skip(st, '(');
        gsym(b);
        gexpr(st);
        c = gtst(st, 0, 0);
        gsym_addr(c, d);
        skip(st, ')');
        gsym(a);
        skip(st, ';');
    } else
    if (tok == TOK_SWITCH) {
        next(st);
        skip(st, '(');
        gexpr(st);
        /* XXX: other types than integer */
        case_reg = gv(st, RC_INT);
        vpop(st);
        skip(st, ')');
        a = 0;
        b = gjmp(st, 0); /* jump to first case */
        c = 0;
        block(st, &a, csym, &b, &c, case_reg, 0);
        /* if no default, jmp after switch */
        if (c == 0)
            c = ind;
        /* default label */
        gsym_addr(b, c);
        /* break label */
        gsym(a);
    } else
    if (tok == TOK_CASE) {
        int v1, v2;
        if (!case_sym)
            expect(st, "switch");
        /* since a case is like a label, we must skip it with a jmp */
        b = gjmp(st, 0);
    next_case:
        next(st);
        v1 = expr_const(st);
        v2 = v1;
        if (gnu_ext && tok == TOK_DOTS) {
            next(st);
            v2 = expr_const(st);
            if (v2 < v1)
                warning(st, "empty case range");
        }
        gsym(*case_sym);
        vseti(st, case_reg, 0);
        vpushi(st, v1);
        if (v1 == v2) {
            gen_op(st, TOK_EQ);
            *case_sym = 0;
        } else {
            gen_op(st, TOK_GE);
            *case_sym = gtst(st, 1, 0);
            vseti(st, case_reg, 0);
            vpushi(st, v2);
            gen_op(st, TOK_LE);
        }
        skip(st, ':');
        if (tok == TOK_CASE) {
            b = gtst(st, 0, b);
            goto next_case;
        }
        *case_sym = gtst(st, 1, *case_sym);
        gsym(b);
        is_expr = 0;
        goto block_after_label;
    } else 
    if (tok == TOK_DEFAULT) {
        next(st);
        skip(st, ':');
        if (!def_sym)
            expect(st, "switch");
        if (*def_sym)
           tcc_error(st, "too many 'default'");
        *def_sym = ind;
        is_expr = 0;
        goto block_after_label;
    } else
    if (tok == TOK_GOTO) {
        next(st);
        if (tok == '*' && gnu_ext) {
            /* computed goto */
            next(st);
            gexpr(st);
            if ((vtop->type.t & VT_BTYPE) != VT_PTR)
                expect(st, "pointer");
            ggoto(st);
        } else if (tok >= TOK_UIDENT) {
            s = label_find(st, tok);
            /* put forward definition if needed */
            if (!s) {
                s = label_push(st, &global_label_stack, tok, LABEL_FORWARD);
            } else {
                if (s->r == LABEL_DECLARED)
                    s->r = LABEL_FORWARD;
            }
            /* label already defined */
            if (s->r & LABEL_FORWARD) 
                s->next = (void *)gjmp(st, (long)s->next);
            else
                gjmp_addr(st, (long)s->next);
            next(st);
        } else {
            expect(st, "label identifier");
        }
        skip(st, ';');
    } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
        asm_instr(st);
    } else {
        b = is_label(st);
        if (b) {
            /* label case */
            s = label_find(st, b);
            if (s) {
                if (s->r == LABEL_DEFINED)
                   tcc_error(st, "duplicate label '%s'", get_tok_str(st, s->v, NULL));
                gsym((long)s->next);
                s->r = LABEL_DEFINED;
            } else {
                s = label_push(st, &global_label_stack, b, LABEL_DEFINED);
            }
            s->next = (void *)ind;
            /* we accept this, but it is a mistake */
        block_after_label:
            if (tok == '}') {
                warning(st, "deprecated use of label at end of compound statement");
            } else {
                if (is_expr)
                    vpop(st);
                block(st, bsym, csym, case_sym, def_sym, case_reg, is_expr);
            }
        } else {
            /* expression case */
            if (tok != ';') {
                if (is_expr) {
                    vpop(st);
                    gexpr(st);
                } else {
                    gexpr(st);
                    vpop(st);
                }
            }
            skip(st, ';');
        }
    }
}

/* t is the array or struct type. c is the array or struct
   address. cur_index/cur_field is the pointer to the current
   value. 'size_only' is true if only size info is needed (only used
   in arrays) */
static void decl_designator(TCCState *st, CType *type, Section *sec, unsigned long c, 
                            int *cur_index, Sym **cur_field, 
                            int size_only)
{
    Sym *s, *f;
    int notfirst, index, index_last, align, l, nb_elems, elem_size;
    CType type1;

    notfirst = 0;
    elem_size = 0;
    nb_elems = 1;
    if (gnu_ext && (l = is_label(st)) != 0)
        goto struct_field;
    while (tok == '[' || tok == '.') {
        if (tok == '[') {
            if (!(type->t & VT_ARRAY))
                expect(st, "array type");
            s = type->ref;
            next(st);
            index = expr_const(st);
            if (index < 0 || (s->c >= 0 && index >= s->c))
                expect(st, "invalid index");
            if (tok == TOK_DOTS && gnu_ext) {
                next(st);
                index_last = expr_const(st);
                if (index_last < 0 || 
                    (s->c >= 0 && index_last >= s->c) ||
                    index_last < index)
                    expect(st, "invalid index");
            } else {
                index_last = index;
            }
            skip(st, ']');
            if (!notfirst)
                *cur_index = index_last;
            type = pointed_type(st, type);
            elem_size = type_size(st, type, &align);
            c += index * elem_size;
            /* NOTE: we only support ranges for last designator */
            nb_elems = index_last - index + 1;
            if (nb_elems != 1) {
                notfirst = 1;
                break;
            }
        } else {
            next(st);
            l = tok;
            next(st);
        struct_field:
            if ((type->t & VT_BTYPE) != VT_STRUCT)
                expect(st, "struct/union type");
            s = type->ref;
            l |= SYM_FIELD;
            f = s->next;
            while (f) {
                if (f->v == l)
                    break;
                f = f->next;
            }
            if (!f)
                expect(st, "field");
            if (!notfirst)
                *cur_field = f;
            /* XXX: fix this mess by using explicit storage field */
            type1 = f->type;
            type1.t |= (type->t & ~VT_TYPE);
            type = &type1;
            c += f->c;
        }
        notfirst = 1;
    }
    if (notfirst) {
        if (tok == '=') {
            next(st);
        } else {
            if (!gnu_ext)
                expect(st, "=");
        }
    } else {
        if (type->t & VT_ARRAY) {
            index = *cur_index;
            type = pointed_type(st, type);
            c += index * type_size(st, type, &align);
        } else {
            f = *cur_field;
            if (!f)
               tcc_error(st, "too many field init");
            /* XXX: fix this mess by using explicit storage field */
            type1 = f->type;
            type1.t |= (type->t & ~VT_TYPE);
            type = &type1;
            c += f->c;
        }
    }
    decl_initializer(st, type, sec, c, 0, size_only);

    /* XXX: make it more general */
    if (!size_only && nb_elems > 1) {
        unsigned long c_end;
        uint8_t *src, *dst;
        int i;

        if (!sec)
           tcc_error(st, "range init not supported yet for dynamic storage");
        c_end = c + nb_elems * elem_size;
        if (c_end > sec->data_allocated)
            section_realloc(st, sec, c_end);
        src = sec->data + c;
        dst = src;
        for(i = 1; i < nb_elems; i++) {
            dst += elem_size;
            memcpy(dst, src, elem_size);
        }
    }
}

#define EXPR_VAL   0
#define EXPR_CONST 1
#define EXPR_ANY   2

/* store a value or an expression directly in global data or in local array */
static void init_putv(TCCState *st, CType *type, Section *sec, unsigned long c, 
                      int v, int expr_type)
{
    int saved_global_expr, bt, bit_pos, bit_size;
    void *ptr;
    unsigned long long bit_mask;
    CType dtype;

    switch(expr_type) {
    case EXPR_VAL:
        vpushi(st, v);
        break;
    case EXPR_CONST:
        /* compound literals must be allocated globally in this case */
        saved_global_expr = global_expr;
        global_expr = 1;
        expr_const1(st);
        global_expr = saved_global_expr;
        /* NOTE: symbols are accepted */
        if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
           tcc_error(st, "initializer element is not constant");
        break;
    case EXPR_ANY:
        expr_eq(st);
        break;
    }

    dtype = *type;
    dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */

    if (sec) {
        /* XXX: not portable */
        /* XXX: generate error if incorrect relocation */
        gen_assign_cast(st, &dtype);
        bt = type->t & VT_BTYPE;
        ptr = sec->data + c;
        /* XXX: make code faster ? */
        if (!(type->t & VT_BITFIELD)) {
            bit_pos = 0;
            bit_size = 32;
            bit_mask = -1LL;
        } else {
            bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
            bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
            bit_mask = (1LL << bit_size) - 1;
        }
        if ((vtop->r & VT_SYM) &&
            (bt == VT_BYTE ||
             bt == VT_SHORT ||
             bt == VT_DOUBLE ||
             bt == VT_LDOUBLE ||
             bt == VT_LLONG ||
             (bt == VT_INT && bit_size != 32)))
           tcc_error(st, "initializer element is not computable at load time");
        switch(bt) {
        case VT_BYTE:
            *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
            break;
        case VT_SHORT:
            *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
            break;
        case VT_DOUBLE:
            *(double *)ptr = vtop->c.d;
            break;
        case VT_LDOUBLE:
            *(long double *)ptr = vtop->c.ld;
            break;
        case VT_LLONG:
            *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
            break;
        default:
            if (vtop->r & VT_SYM) {
                greloc(st, sec, vtop->sym, c, R_DATA_32);
            }
            *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
            break;
        }
        vtop--;
    } else {
        vset(st, &dtype, VT_LOCAL|VT_LVAL, c);
        vswap(st);
        vstore(st);
        vpop(st);
    }
}

/* put zeros for variable based init */
static void init_putz(TCCState *st, CType *t, Section *sec, unsigned long c, int size)
{
    if (sec) {
        /* nothing to do because globals are already set to zero */
    } else {
        vpush_global_sym(st, &func_old_type, TOK_memset);
        vseti(st, VT_LOCAL, c);
        vpushi(st, 0);
        vpushi(st, size);
        gfunc_call(st, 3);
    }
}

/* 't' contains the type and storage info. 'c' is the offset of the
   object in section 'sec'. If 'sec' is NULL, it means stack based
   allocation. 'first' is true if array '{' must be read (multi
   dimension implicit array init handling). 'size_only' is true if
   size only evaluation is wanted (only for arrays). */
static void decl_initializer(TCCState *st, CType *type, Section *sec, unsigned long c, 
                             int first, int size_only)
{
    int index, array_length, n, no_oblock, nb, parlevel, i;
    int size1, align1, expr_type;
    Sym *s, *f;
    CType *t1;

    if (type->t & VT_ARRAY) {
        s = type->ref;
        n = s->c;
        array_length = 0;
        t1 = pointed_type(st, type);
        size1 = type_size(st, t1, &align1);

        no_oblock = 1;
        if ((first && tok != TOK_LSTR && tok != TOK_STR) || 
            tok == '{') {
            skip(st, '{');
            no_oblock = 0;
        }

        /* only parse strings here if correct type (otherwise: handle
           them as ((w)char *) expressions */
        if ((tok == TOK_LSTR && 
#ifdef WIN32
             (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)) ||
#else
             (t1->t & VT_BTYPE) == VT_INT) ||
#endif
            (tok == TOK_STR &&
             (t1->t & VT_BTYPE) == VT_BYTE)) {
            while (tok == TOK_STR || tok == TOK_LSTR) {
                int cstr_len, ch;
                CString *cstr;

                cstr = tokc.cstr;
                /* compute maximum number of chars wanted */
                if (tok == TOK_STR)
                    cstr_len = cstr->size;
                else
                    cstr_len = cstr->size / sizeof(nwchar_t);
                cstr_len--;
                nb = cstr_len;
                if (n >= 0 && nb > (n - array_length))
                    nb = n - array_length;
                if (!size_only) {
                    if (cstr_len > nb)
                        warning(st, "initializer-string for array is too long");
                    /* in order to go faster for common case (char
                       string in global variable, we handle it
                       specifically */
                    if (sec && tok == TOK_STR && size1 == 1) {
                        memcpy(sec->data + c + array_length, cstr->data, nb);
                    } else {
                        for(i=0;i<nb;i++) {
                            if (tok == TOK_STR)
                                ch = ((unsigned char *)cstr->data)[i];
                            else
                                ch = ((nwchar_t *)cstr->data)[i];
                            init_putv(st, t1, sec, c + (array_length + i) * size1,
                                      ch, EXPR_VAL);
                        }
                    }
                }
                array_length += nb;
                next(st);
            }
            /* only add trailing zero if enough storage (no
               warning in this case since it is standard) */
            if (n < 0 || array_length < n) {
                if (!size_only) {
                    init_putv(st, t1, sec, c + (array_length * size1), 0, EXPR_VAL);
                }
                array_length++;
            }
        } else {
            index = 0;
            while (tok != '}') {
                decl_designator(st, type, sec, c, &index, NULL, size_only);
                if (n >= 0 && index >= n)
                   tcc_error(st, "index too large");
                /* must put zero in holes (note that doing it that way
                   ensures that it even works with designators) */
                if (!size_only && array_length < index) {
                    init_putz(st, t1, sec, c + array_length * size1, 
                              (index - array_length) * size1);
                }
                index++;
                if (index > array_length)
                    array_length = index;
                /* special test for multi dimensional arrays (may not
                   be strictly correct if designators are used at the
                   same time) */
                if (index >= n && no_oblock)
                    break;
                if (tok == '}')
                    break;
                skip(st, ',');
            }
        }
        if (!no_oblock)
            skip(st, '}');
        /* put zeros at the end */
        if (!size_only && n >= 0 && array_length < n) {
            init_putz(st, t1, sec, c + array_length * size1, 
                      (n - array_length) * size1);
        }
        /* patch type size if needed */
        if (n < 0)
            s->c = array_length;
    } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
               (sec || !first || tok == '{')) {
        int par_count;

        /* NOTE: the previous test is a specific case for automatic
           struct/union init */
        /* XXX: union needs only one init */

        /* XXX: this test is incorrect for local initializers
           beginning with ( without {. It would be much more difficult
           to do it correctly (ideally, the expression parser should
           be used in all cases) */
        par_count = 0;
        if (tok == '(') {
            AttributeDef ad1;
            CType type1;
            next(st);
            while (tok == '(') {
                par_count++;
                next(st);
            }
            if (!parse_btype(st, &type1, &ad1))
                expect(st, "cast");
            type_decl(st, &type1, &ad1, &n, TYPE_ABSTRACT);
#if 0
            if (!is_assignable_types(type, &type1))
               tcc_error(st, "invalid type for cast");
#endif
            skip(st, ')');
        }
        no_oblock = 1;
        if (first || tok == '{') {
            skip(st, '{');
            no_oblock = 0;
        }
        s = type->ref;
        f = s->next;
        array_length = 0;
        index = 0;
        n = s->c;
        while (tok != '}') {
            decl_designator(st, type, sec, c, NULL, &f, size_only);
            index = f->c;
            if (!size_only && array_length < index) {
                init_putz(st, type, sec, c + array_length, 
                          index - array_length);
            }
            index = index + type_size(st, &f->type, &align1);
            if (index > array_length)
                array_length = index;
            f = f->next;
            if (no_oblock && f == NULL)
                break;
            if (tok == '}')
                break;
            skip(st, ',');
        }
        /* put zeros at the end */
        if (!size_only && array_length < n) {
            init_putz(st, type, sec, c + array_length, 
                      n - array_length);
        }
        if (!no_oblock)
            skip(st, '}');
        while (par_count) {
            skip(st, ')');
            par_count--;
        }
    } else if (tok == '{') {
        next(st);
        decl_initializer(st, type, sec, c, first, size_only);
        skip(st, '}');
    } else if (size_only) {
        /* just skip expression */
        parlevel = 0;
        while ((parlevel > 0 || (tok != '}' && tok != ',')) && 
               tok != -1) {
            if (tok == '(')
                parlevel++;
            else if (tok == ')')
                parlevel--;
            next(st);
        }
    } else {
        /* currently, we always use constant expression for globals
           (may change for scripting case) */
        expr_type = EXPR_CONST;
        if (!sec)
            expr_type = EXPR_ANY;
        init_putv(st, type, sec, c, 0, expr_type);
    }
}

/* parse an initializer for type 't' if 'has_init' is non zero, and
   allocate space in local or global data space ('r' is either
   VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
   variable 'v' of scope 'scope' is declared before initializers are
   parsed. If 'v' is zero, then a reference to the new object is put
   in the value stack. If 'has_init' is 2, a special parsing is done
   to handle string constants. */
static void decl_initializer_alloc(TCCState *st, CType *type, AttributeDef *ad, int r, 
                                   int has_init, int v, int scope)
{
    int size, align, addr, data_offset;
    int level;
    ParseState saved_parse_state;
    TokenString init_str;
    Section *sec;

    size = type_size(st, type, &align);
    /* If unknown size, we must evaluate it before
       evaluating initializers because
       initializers can generate global data too
       (e.g. string pointers or ISOC99 compound
       literals). It also simplifies local
       initializers handling */
    tok_str_new(st, &init_str);
    if (size < 0) {
        if (!has_init) 
           tcc_error(st, "unknown type size");
        /* get all init string */
        if (has_init == 2) {
            /* only get strings */
            while (tok == TOK_STR || tok == TOK_LSTR) {
                tok_str_add_tok(st, &init_str);
                next(st);
            }
        } else {
            level = 0;
            while (level > 0 || (tok != ',' && tok != ';')) {
                if (tok < 0)
                   tcc_error(st, "unexpected end of file in initializer");
                tok_str_add_tok(st, &init_str);
                if (tok == '{')
                    level++;
                else if (tok == '}') {
                    if (level == 0)
                        break;
                    level--;
                }
                next(st);
            }
        }
        tok_str_add(st, &init_str, -1, 0);
        tok_str_add(st, &init_str, 0, 0);
        
        /* compute size */
        save_parse_state(st, &saved_parse_state);

        macro_ptr = init_str.str;
        next(st);
        decl_initializer(st, type, NULL, 0, 1, 1);
        /* prepare second initializer parsing */
        macro_ptr = init_str.str;
        next(st);
        
        /* if still unknown size, error */
        size = type_size(st, type, &align);
        if (size < 0) 
           tcc_error(st, "unknown type size");
    }
    /* take into account specified alignment if bigger */
    if (ad->aligned) {
        if (ad->aligned > align)
            align = ad->aligned;
    } else if (ad->packed) {
        align = 1;
    }
    if ((r & VT_VALMASK) == VT_LOCAL) {
        sec = NULL;
        if (do_bounds_check && (type->t & VT_ARRAY)) 
            loc--;
        loc = (loc - size) & -align;
        addr = loc;
        /* handles bounds */
        /* XXX: currently, since we do only one pass, we cannot track
           '&' operators, so we add only arrays */
        if (do_bounds_check && (type->t & VT_ARRAY)) {
            unsigned long *bounds_ptr;
            /* add padding between regions */
            loc--;
            /* then add local bound info */
            bounds_ptr = section_ptr_add(st, lbounds_section, 2 * sizeof(unsigned long));
            bounds_ptr[0] = addr;
            bounds_ptr[1] = size;
        }
        if (v) {
            /* local variable */
            sym_push(st, v, type, r, addr);
        } else {
            /* push local reference */
            vset(st, type, r, addr);
        }
    } else {
        Sym *sym;

        sym = NULL;
        if (v && scope == VT_CONST) {
            /* see if the symbol was already defined */
            sym = sym_find(st, v);
            if (sym) {
                if (!is_compatible_types(st, &sym->type, type))
                   tcc_error(st, "incompatible types for redefinition of '%s'", 
                          get_tok_str(st, v, NULL));
                if (sym->type.t & VT_EXTERN) {
                    /* if the variable is extern, it was not allocated */
                    sym->type.t &= ~VT_EXTERN;
                    /* set array size if it was ommited in extern
                       declaration */
                    if ((sym->type.t & VT_ARRAY) && 
                        sym->type.ref->c < 0 &&
                        type->ref->c >= 0)
                        sym->type.ref->c = type->ref->c;
                } else {
                    /* we accept several definitions of the same
                       global variable. this is tricky, because we
                       must play with the SHN_COMMON type of the symbol */
                    /* XXX: should check if the variable was already
                       initialized. It is incorrect to initialized it
                       twice */
                    /* no init data, we won't add more to the symbol */
                    if (!has_init)
                        goto no_alloc;
                }
            }
        }

        /* allocate symbol in corresponding section */
        sec = ad->section;
        if (!sec) {
            if (has_init)
                sec = data_section;
            else if (st->nocommon)
                sec = bss_section;
        }
        if (sec) {
            data_offset = sec->data_offset;
            data_offset = (data_offset + align - 1) & -align;
            addr = data_offset;
            /* very important to increment global pointer at this time
               because initializers themselves can create new initializers */
            data_offset += size;
            /* add padding if bound check */
            if (do_bounds_check)
                data_offset++;
            sec->data_offset = data_offset;
            /* allocate section space to put the data */
            if (sec->sh_type != SHT_NOBITS && 
                data_offset > sec->data_allocated)
                section_realloc(st, sec, data_offset);
            /* align section if needed */
            if (align > sec->sh_addralign)
                sec->sh_addralign = align;
        } else {
            addr = 0; /* avoid warning */
        }

        if (v) {
            if (scope != VT_CONST || !sym) {
                sym = sym_push(st, v, type, r | VT_SYM, 0);
            }
            /* update symbol definition */
            if (sec) {
                put_extern_sym(st, sym, sec, addr, size);
            } else {
                Elf32_Sym *esym;
                /* put a common area */
                put_extern_sym(st, sym, NULL, align, size);
                /* XXX: find a nicer way */
                esym = &((Elf32_Sym *)symtab_section->data)[sym->c];
                esym->st_shndx = SHN_COMMON;
            }
        } else {
            CValue cval;

            /* push global reference */
            sym = get_sym_ref(st, type, sec, addr, size);
            cval.ul = 0;
            vsetc(st, type, VT_CONST | VT_SYM, &cval);
            vtop->sym = sym;
        }

        /* handles bounds now because the symbol must be defined
           before for the relocation */
        if (do_bounds_check) {
            unsigned long *bounds_ptr;

            greloc(st, bounds_section, sym, bounds_section->data_offset, R_DATA_32);
            /* then add global bound info */
            bounds_ptr = section_ptr_add(st, bounds_section, 2 * sizeof(long));
            bounds_ptr[0] = 0; /* relocated */
            bounds_ptr[1] = size;
        }
    }
    if (has_init) {
        decl_initializer(st, type, sec, addr, 1, 0);
        /* restore parse state if needed */
        if (init_str.str) {
            tok_str_free(st, init_str.str);
            restore_parse_state(st, &saved_parse_state);
        }
    }
 no_alloc: ;
}

void put_func_debug(TCCState *st, Sym *sym)
{
    char buf[512];

    /* stabs info */
    /* XXX: we put here a dummy type */
    snprintf(buf, sizeof(buf), "%s:%c1", 
             funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
    put_stabs_r(st, buf, N_FUN, 0, file->line_num, 0,
                cur_text_section, sym->c);
    last_ind = 0;
    last_line_num = 0;
}

/* parse an old style function declaration list */
/* XXX: check multiple parameter */
static void func_decl_list(TCCState *st, Sym *func_sym)
{
    AttributeDef ad;
    int v;
    Sym *s;
    CType btype, type;

    /* parse each declaration */
    while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
        if (!parse_btype(st, &btype, &ad)) 
            expect(st, "declaration list");
        if (((btype.t & VT_BTYPE) == VT_ENUM ||
             (btype.t & VT_BTYPE) == VT_STRUCT) && 
            tok == ';') {
            /* we accept no variable after */
        } else {
            for(;;) {
                type = btype;
                type_decl(st, &type, &ad, &v, TYPE_DIRECT);
                /* find parameter in function parameter list */
                s = func_sym->next;
                while (s != NULL) {
                    if ((s->v & ~SYM_FIELD) == v)
                        goto found;
                    s = s->next;
                }
               tcc_error(st, "declaration for parameter '%s' but no such parameter",
                      get_tok_str(st, v, NULL));
            found:
                /* check that no storage specifier except 'register' was given */
                if (type.t & VT_STORAGE)
                   tcc_error(st, "storage class specified for '%s'", get_tok_str(st, v, NULL)); 
                convert_parameter_type(st, &type);
                /* we can add the type (NOTE: it could be local to the function) */
                s->type = type;
                /* accept other parameters */
                if (tok == ',')
                    next(st);
                else
                    break;
            }
        }
        skip(st, ';');
    }
}

/* parse a function defined by symbol 'sym' and generate its code in
   'cur_text_section' */
static void gen_function(TCCState *st, Sym *sym)
{
    ind = cur_text_section->data_offset;
    /* NOTE: we patch the symbol size later */
    put_extern_sym(st, sym, cur_text_section, ind, 0);
    funcname = get_tok_str(st, sym->v, NULL);
    func_ind = ind;
    /* put debug symbol */
    if (do_debug)
        put_func_debug(st, sym);
    /* push a dummy symbol to enable local sym storage */
    sym_push2(st, &local_stack, SYM_FIELD, 0, 0);
    gfunc_prolog(st, &sym->type);
    rsym = 0;
    block(st, NULL, NULL, NULL, NULL, 0, 0);
    gsym(rsym);
    gfunc_epilog(st);
    cur_text_section->data_offset = ind;
    label_pop(st, &global_label_stack, NULL);
    sym_pop(st, &local_stack, NULL); /* reset local stack */
    /* end of function */
    /* patch symbol size */
    ((Elf32_Sym *)symtab_section->data)[sym->c].st_size = 
        ind - func_ind;
    if (do_debug) {
        put_stabn(st, N_FUN, 0, 0, ind - func_ind);
    }
    funcname = ""; /* for safety */
    func_vt.t = VT_VOID; /* for safety */
    ind = 0; /* for safety */
}

static void gen_inline_functions(TCCState *st)
{
    Sym *sym;
    CType *type;
    int *str, inline_generated;

    /* iterate while inline function are referenced */
    for(;;) {
        inline_generated = 0;
        for(sym = global_stack; sym != NULL; sym = sym->prev) {
            type = &sym->type;
            if (((type->t & VT_BTYPE) == VT_FUNC) &&
                (type->t & (VT_STATIC | VT_INLINE)) == 
                (VT_STATIC | VT_INLINE) &&
                sym->c != 0) {
                /* the function was used: generate its code and
                   convert it to a normal function */
                str = (int *)sym->r;
                sym->r = VT_SYM | VT_CONST;
                type->t &= ~VT_INLINE;

                macro_ptr = str;
                next(st);
                cur_text_section = text_section;
                gen_function(st, sym);
                macro_ptr = NULL; /* fail safe */

                tok_str_free(st, str);
                inline_generated = 1;
            }
        }
        if (!inline_generated)
            break;
    }

    /* free all remaining inline function tokens */
    for(sym = global_stack; sym != NULL; sym = sym->prev) {
        type = &sym->type;
        if (((type->t & VT_BTYPE) == VT_FUNC) &&
            (type->t & (VT_STATIC | VT_INLINE)) == 
            (VT_STATIC | VT_INLINE)) {
            str = (int *)sym->r;
            tok_str_free(st, str);
            sym->r = 0; /* fail safe */
        }
    }
}

/* 'l' is VT_LOCAL or VT_CONST to define default storage type */
static void decl(TCCState *st, int l)
{
    int v, has_init, r;
    CType type, btype;
    Sym *sym;
    AttributeDef ad;
    
    while (1) {
        if (!parse_btype(st, &btype, &ad)) {
            /* skip redundant ';' */
            /* XXX: find more elegant solution */
            if (tok == ';') {
                next(st);
                continue;
            }
            if (l == VT_CONST &&
                (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
                /* global asm block */
                asm_global_instr(st);
                continue;
            }
            /* special test for old K&R protos without explicit int
               type. Only accepted when defining global data */
            if (l == VT_LOCAL || tok < TOK_DEFINE)
                break;
            btype.t = VT_INT;
        }
        if (((btype.t & VT_BTYPE) == VT_ENUM ||
             (btype.t & VT_BTYPE) == VT_STRUCT) && 
            tok == ';') {
            /* we accept no variable after */
            next(st);
            continue;
        }
        while (1) { /* iterate thru each declaration */
            type = btype;
            type_decl(st, &type, &ad, &v, TYPE_DIRECT);
#if 0
            {
                char buf[500];
                type_to_str(st, buf, sizeof(buf), &type, get_tok_str(st, v, NULL));
                printf("type = '%s'\n", buf);
            }
#endif
            if ((type.t & VT_BTYPE) == VT_FUNC) {
                /* if old style function prototype, we accept a
                   declaration list */
                sym = type.ref;
                if (sym->c == FUNC_OLD)
                    func_decl_list(st, sym);
            }

            /* Open curly bracket here can only be a function body, because
               struct and union contents are handled by parse_btype(st) above. */
            if (tok == '{') {
                if (l == VT_LOCAL)
                   tcc_error(st, "cannot use local functions");
                if ((type.t & VT_BTYPE) != VT_FUNC)
                    expect(st, "function definition");

                /* reject abstract declarators in function definition */
                sym = type.ref;
                while ((sym = sym->next) != NULL)
                    if (!(sym->v & ~SYM_FIELD))
                       expect(st, "identifier");
                
                /* XXX: cannot do better now: convert extern inline to static inline */
                if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
                    type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
                
                sym = sym_find(st, v);
                if (sym) {
                    if ((sym->type.t & VT_BTYPE) != VT_FUNC)
                        goto func_error1;
                    /* specific case: if not func_call defined, we put
                       the one of the prototype */
                    /* XXX: should have default value */
                    if (sym->type.ref->r != FUNC_CDECL &&
                        type.ref->r == FUNC_CDECL)
                        type.ref->r = sym->type.ref->r;
                    if (!is_compatible_types(st, &sym->type, &type)) {
                    func_error1:
                       tcc_error(st, "incompatible types for redefinition of '%s'", 
                              get_tok_str(st, v, NULL));
                    }
                    /* if symbol is already defined, then put complete type */
                    sym->type = type;
                } else {
                    /* put function symbol */
                    sym = global_identifier_push(st, v, type.t, 0);
                    sym->type.ref = type.ref;
                }

                /* static inline functions are just recorded as a kind
                   of macro. Their code will be emitted at the end of
                   the compilation unit only if they are used */
                if ((type.t & (VT_INLINE | VT_STATIC)) == 
                    (VT_INLINE | VT_STATIC)) {
                    TokenString func_str;
                    int block_level;
                           
                    tok_str_new(st, &func_str);
                    
                    block_level = 0;
                    for(;;) {
                        int t;
                        if (tok == TOK_EOF)
                           tcc_error(st, "unexpected end of file");
                        tok_str_add_tok(st, &func_str);
                        t = tok;
                        next(st);
                        if (t == '{') {
                            block_level++;
                        } else if (t == '}') {
                            block_level--;
                            if (block_level == 0)
                                break;
                        }
                    }
                    tok_str_add(st, &func_str, -1, 0);
                    tok_str_add(st, &func_str, 0, 0);
                    sym->r = (int)func_str.str;
                } else {
                    /* compute text section */
                    cur_text_section = ad.section;
                    if (!cur_text_section)
                        cur_text_section = text_section;
                    sym->r = VT_SYM | VT_CONST;
                    gen_function(st, sym);
#ifdef WIN32
                    if (ad.dllexport) {
                        ((Elf32_Sym *)symtab_section->data)[sym->c].st_other |= 1;
                    }
#endif
                }
                break;

            /* If there was no function body, it must be a varaible. */
            } else {
                if (btype.t & VT_TYPEDEF) {
                    /* save typedefed type  */
                    /* XXX: test storage specifiers ? */
                    sym = sym_push(st, v, &type, 0, 0);
                    sym->type.t |= VT_TYPEDEF;
                } else if ((type.t & VT_BTYPE) == VT_FUNC) {
                    /* external function definition */
                    /* specific case for func_call attribute */
                    if (ad.func_call)
                        type.ref->r = ad.func_call;
                    external_sym(st, v, &type, 0);
                } else {
                    /* not lvalue if array */
                    r = 0;
                    if (!(type.t & VT_ARRAY))
                        r |= lvalue_type(st, type.t);
                    has_init = (tok == '=');
                    if ((btype.t & VT_EXTERN) || 
                        ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
                         !has_init && l == VT_CONST && type.ref->c < 0)) {
                        /* external variable */
                        /* NOTE: as GCC, uninitialized global static
                           arrays of null size are considered as
                           extern */
                        external_sym(st, v, &type, r);
                    } else {
                        type.t |= (btype.t & VT_STATIC); /* Retain "static". */
                        if (type.t & VT_STATIC)
                            r |= VT_CONST;
                        else
                            r |= l;
                        if (has_init)
                            next(st);
                        decl_initializer_alloc(st, &type, &ad, r, 
                                               has_init, v, l);
                    }
                }
                if (tok != ',') {
                    skip(st, ';');
                    break;
                }
                next(st);
            }
        }
    }
}

/* better than nothing, but needs extension to handle '-E' option
   correctly too */
static void preprocess_init(TCCState *st)
{
    st->include_stack_ptr = st->include_stack;
    /* XXX: move that before to avoid having to initialize
       file->ifdef_stack_ptr ? */
    st->ifdef_stack_ptr = st->ifdef_stack;
    file->ifdef_stack_ptr = st->ifdef_stack_ptr;

    vtop = vstack;
    st->pack_stack[0] = 0;
    st->pack_stack_ptr = st->pack_stack;
}

/* compile the C file opened in 'file'. Return non zero if errors. */
static int tcc_compile(TCCState *st)
{
    Sym *define_start;
    char buf[512];
    volatile int section_sym;

    preprocess_init(st);

    funcname = "";
    anon_sym = SYM_FIRST_ANOM; 

    /* file info: full path + filename */
    section_sym = 0; /* avoid warning */
    if (do_debug) {
        section_sym = put_elf_sym(st, symtab_section, 0, 0, 
                                  ELF32_ST_INFO(STB_LOCAL, STT_SECTION), 0, 
                                  text_section->sh_num, NULL);
        getcwd(buf, sizeof(buf));
        pstrcat(st, buf, sizeof(buf), "/");
        put_stabs_r(st, buf, N_SO, 0, 0, 
                    text_section->data_offset, text_section, section_sym);
        put_stabs_r(st, file->filename, N_SO, 0, 0, 
                    text_section->data_offset, text_section, section_sym);
    }
    /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
       symbols can be safely used */
    put_elf_sym(st, symtab_section, 0, 0, 
                ELF32_ST_INFO(STB_LOCAL, STT_FILE), 0, 
                SHN_ABS, file->filename);

    /* define some often used types */

    
    int_type.t = VT_INT;

    char_pointer_type.t = VT_BYTE;
    mk_pointer(st, &char_pointer_type);

    func_old_type.t = VT_FUNC;
    func_old_type.ref = sym_push(st, SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);

#if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
    float_type.t = VT_FLOAT;
    double_type.t = VT_DOUBLE;

    func_float_type.t = VT_FUNC;
    func_float_type.ref = sym_push(st, SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
    func_double_type.t = VT_FUNC;
    func_double_type.ref = sym_push(st, SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
#endif

#if 0
    /* define 'void *alloca(unsigned int)' builtin function */
    {
        Sym *st;

        p = anon_sym++;
        sym = sym_push(st, p, mk_pointer(st, VT_VOID), FUNC_CDECL, FUNC_NEW);
        st = sym_push(st, SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
        st->next = NULL;
        sym->next = st;
        sym_push(st, TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
    }
#endif

    define_start = define_stack;

    if (setjmp(st->error_jmp_buf) == 0) {
        st->nb_errors = 0;
        st->error_set_jmp_enabled = 1;

        fch = file->buf_ptr[0];
        next_tok_flags = TOK_FLAG_BOW | TOK_FLAG_BOL | TOK_FLAG_BOF;
        parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
        next(st);
        decl(st, VT_CONST);
        if (tok != TOK_EOF) expect(st, "declaration");

        /* end of translation unit info */
        if (do_debug) {
            put_stabs_r(st, NULL, N_SO, 0, 0, text_section->data_offset,
                        text_section, section_sym);
        }
    }
    st->error_set_jmp_enabled = 0;

    /* reset define stack, but leave -Dsymbols (may be incorrect if
       they are undefined) */
    free_defines(st, define_start); 

    gen_inline_functions(st);

    sym_pop(st, &global_stack, NULL);

    return st->nb_errors != 0 ? -1 : 0;
}

/* Preprocess the current file */
/* XXX: add line and file infos, add options to preserve spaces */
static int tcc_preprocess(TCCState *st)
{
    Sym *define_start;
    int last_is_space;

    preprocess_init(st);

    define_start = define_stack;

    fch = file->buf_ptr[0];
    tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
    parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
        PARSE_FLAG_LINEFEED;
    last_is_space = 1;
    next(st);
    for(;;) {
        if (tok == TOK_EOF)
            break;
        if (!last_is_space) {
            fputc(' ', st->outfile);
        }
        fputs(get_tok_str(st, tok, &tokc), st->outfile);
        if (tok == TOK_LINEFEED) {
            last_is_space = 1;
            /* XXX: suppress that hack */
            parse_flags &= ~PARSE_FLAG_LINEFEED;
            next(st);
            parse_flags |= PARSE_FLAG_LINEFEED;
        } else {
            last_is_space = 0;
            next(st);
        }
    }

    free_defines(st, define_start);

    return 0;
}

#ifdef LIBTCC
int tcc_compile_string(TCCState *s, const char *str)
{
    BufferedFile bf1, *bf = &bf1;
    int ret, len;
    char *buf;

    /* init file structure */
    bf->fd = NULL;
    /* XXX: avoid copying */
    len = strlen(str);
    buf = tcc_malloc(s, len + 1);
    if (!buf)
        return -1;
    memcpy(buf, str, len);
    buf[len] = CH_EOB;
    bf->buf_ptr = buf;
    bf->buf_end = buf + len;
    pstrcpy(s,  bf->filename, sizeof(bf->filename), "<string>");
    bf->line_num = 1;
    file = bf;
    
    ret = tcc_compile(s);
    
    ckfree((char *)buf);

    /* currently, no need to close */
    return ret;
}
#endif

/* define a preprocessor symbol. A value can also be provided with the '=' operator */
void tcc_define_symbol(TCCState *st, const char *sym, const char *value)
{
    BufferedFile bf1, *bf = &bf1;

    pstrcpy(st,  bf->buffer, IO_BUF_SIZE, sym);
    pstrcat(st, bf->buffer, IO_BUF_SIZE, " ");
    /* default value */
    if (!value) 
        value = "1";
    pstrcat(st, bf->buffer, IO_BUF_SIZE, value);
    
    /* init file structure */
    bf->fd = NULL;
    bf->buf_ptr = bf->buffer;
    bf->buf_end = bf->buffer + strlen(bf->buffer);
    *bf->buf_end = CH_EOB;
    bf->filename[0] = '\0';
    bf->line_num = 1;
    file = bf;
    
    st->include_stack_ptr = st->include_stack;

    /* parse with define parser */
    fch = file->buf_ptr[0];
    next_nomacro(st);
    parse_define(st);
    file = NULL;
}

/* undefine a preprocessor symbol */
void tcc_undefine_symbol(TCCState *st, const char *sym)
{
    TokenSym *ts;
    Sym *s;
    ts = tok_alloc(st, sym, strlen(sym));
    s = define_find(st, ts->tok);
    /* undefine symbol by putting an invalid name */
    if (s)
        define_undef(s);
}

#ifdef CONFIG_TCC_ASM

#ifdef TCC_TARGET_I386
#include "i386/i386-asm.c"
#endif
#include "tccasm.c"

#else
static void asm_instr(TCCState *st)
{
   tcc_error(st, "inline asm() not supported");
}
static void asm_global_instr(TCCState *st)
{
   tcc_error(st, "inline asm() not supported");
}
#endif

#include "tccelf.c"

#ifdef TCC_TARGET_COFF
#include "tcccoff.c"
#endif

#ifdef WIN32
#include "win32/tccpe.c"
#endif

/* do all relocations (needed before using tcc_get_symbol(st)) */
int tcc_relocate(TCCState *st)
{
    Section *s;
    int i;

    st->nb_errors = 0;
    
#ifdef WIN32
    pe_add_runtime(st);
#else
    tcc_add_runtime(st);
#endif

    relocate_common_syms();
    tcc_add_linker_symbols(st);
    build_got_entries(st);
    
    /* compute relocation address : section are relocated in place. We
       also alloc the bss space */
    for(i = 1; i < st->nb_sections; i++) {
        s = st->sections[i];
        if (s->sh_flags & SHF_ALLOC) {
            if (s->sh_type == SHT_NOBITS)
                s->data = tcc_mallocz(st, s->data_offset);
            s->sh_addr = (unsigned long)s->data;
        }
    }

    relocate_syms(st, 1);

    if (st->nb_errors != 0)
        return -1;

    /* relocate each section */
    for(i = 1; i < st->nb_sections; i++) {
        s = st->sections[i];
        if (s->reloc)
            relocate_section(st, s);
    }

    /* mark executable sections as executable in memory */
    for(i = 1; i < st->nb_sections; i++) {
        s = st->sections[i];
        if ((s->sh_flags & (SHF_ALLOC | SHF_EXECINSTR)) == 
            (SHF_ALLOC | SHF_EXECINSTR)) {
#ifdef WIN32
            {
                int old_protect;
                VirtualProtect(s->data, s->data_offset,
                               PAGE_EXECUTE_READWRITE, &old_protect);
            }
#else
            {
                unsigned long start, end;
                start = (unsigned long)(s->data) & ~(PAGESIZE - 1);
                end = (unsigned long)(s->data + s->data_offset);
                end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
                mprotect((void *)start, end - start, 
                         PROT_READ | PROT_WRITE | PROT_EXEC);
            }
#endif            
        }
    }
    return 0;
}

/* launch the compiled program with the given arguments */
int tcc_run(TCCState *st, int argc, char **argv)
{
    int (*prog_main)(int, char **);

    if (tcc_relocate(st) < 0)
        return -1;

    prog_main = tcc_get_symbol_err(st, "main");
    
#if 0
    if (do_bounds_check) {
        void (*bound_init)(void);

        /* set error function */
        rt_bound_error_msg = (void *)tcc_get_symbol_err(st, 
                                                        "__bound_error_msg");

        /* XXX: use .init section so that it also work in binary ? */
        bound_init = (void *)tcc_get_symbol_err(st, "__bound_init");
        bound_init(st);
    }
#endif
    return (*prog_main)(argc, argv);
}

TCCState *tcc_new(Tcl_Obj * libpath)
{
    const char *p, *r;
    TCCState *s;
    TokenSym *ts;
    int i, c;

    s = tcc_mallocz(NULL, sizeof(TCCState));
    if (!s)
        return NULL;
    s->output_type = TCC_OUTPUT_MEMORY;

    Tcl_IncrRefCount(libpath);
    s->tcc_lib_path = libpath ;

    /* init isid table */
    for(i=0;i<256;i++)
        isidnum_table[i] = isid(s, i) || isnum(s, i);

    /* add all tokens */
    table_ident = NULL;
    memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
    
    tok_ident = TOK_IDENT;
    p = tcc_keywords;
    while (*p) {
        r = p;
        for(;;) {
            c = *r++;
            if (c == '\0')
                break;
        }
        ts = tok_alloc(s, p, r - p - 1);
        p = r;
    }

    /* we add dummy defines for some special macros to speed up tests
       and to have working defined() */
    define_push(s, TOK___LINE__, MACRO_OBJ, NULL, NULL);
    define_push(s, TOK___FILE__, MACRO_OBJ, NULL, NULL);
    define_push(s, TOK___DATE__, MACRO_OBJ, NULL, NULL);
    define_push(s, TOK___TIME__, MACRO_OBJ, NULL, NULL);

    /* standard defines */
    tcc_define_symbol(s, "__STDC__", NULL);
    tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
#if defined(TCC_TARGET_I386)
    tcc_define_symbol(s, "__i386__", NULL);
#endif
#if defined(TCC_TARGET_ARM)
    tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
    tcc_define_symbol(s, "__arm_elf__", NULL);
    tcc_define_symbol(s, "__arm_elf", NULL);
    tcc_define_symbol(s, "arm_elf", NULL);
    tcc_define_symbol(s, "__arm__", NULL);
    tcc_define_symbol(s, "__arm", NULL);
    tcc_define_symbol(s, "arm", NULL);
    tcc_define_symbol(s, "__APCS_32__", NULL);
#endif
#if defined(linux)
    tcc_define_symbol(s, "__linux__", NULL);
    tcc_define_symbol(s, "linux", NULL);
#endif
    /* tiny C specific defines */
    tcc_define_symbol(s, "__TINYC__", NULL);

    /* tiny C & gcc defines */
    tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
    tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
#ifdef WIN32
    tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
#else
    tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
#endif
    
    /* default library paths */
    {
        char buf[1024];
        snprintf(buf, sizeof(buf), "%s/lib", Tcl_GetString(s->tcc_lib_path));
        /* printf("default libraries %s\n",buf); */
        tcc_add_library_path(s, buf);
    }
#ifndef WIN32
    tcc_add_library_path(s, "/usr/local/lib");
    tcc_add_library_path(s, "/usr/lib");
    tcc_add_library_path(s, "/lib");
#endif

    /* no section zero */
    dynarray_add(s, (void ***)&s->sections, &s->nb_sections, NULL);

    /* create standard sections */
    text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
    data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
    bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);

    /* symbols are always generated for linking stage */
    symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
                                ".strtab",
                                ".hashtab", SHF_PRIVATE); 
    strtab_section = symtab_section->link;
    
    /* private symbol table for dynamic symbols */
    s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
                                      ".dynstrtab", 
                                      ".dynhashtab", SHF_PRIVATE);
    s->alacarte_link = 1;

#ifdef CHAR_IS_UNSIGNED
    s->char_is_unsigned = 1;
#endif
#if defined(WIN32) && 0
    /* XXX: currently the PE linker is not ready to support that */
    s->leading_underscore = 1;
#endif
    return s;
}

void tcc_delete(TCCState *st)
{
    /* this leaks but allows you to reuse handles without crashing the process */
    int i, n;

    /* free -D defines */
    free_defines(st, NULL);

    /* free tokens */
    if(0) {
    n = tok_ident - TOK_IDENT;
    for(i = 0; i < n; i++)
        ckfree((char *)(table_ident[i]));
    ckfree((char *)table_ident);

    /* free all sections */


        free_section(st, symtab_section->hash);

        free_section(st, st->dynsymtab_section->hash);
        free_section(st, st->dynsymtab_section->link);
        free_section(st, st->dynsymtab_section);

        for(i = 1; i < st->nb_sections; i++)
            free_section(st, st->sections[i]);
        ckfree((char *)(st->sections));
    }
    
    /* free loaded dlls array */
    for(i = 0; i < st->nb_loaded_dlls; i++)
        ckfree((char *)(st->loaded_dlls[i]));
    ckfree((char *)(st->loaded_dlls));

    /* library paths */
    for(i = 0; i < st->nb_library_paths; i++)
        ckfree((char *)(st->library_paths[i]));
    ckfree((char *)(st->library_paths));

    /* cached includes */
    for(i = 0; i < st->nb_cached_includes; i++)
        ckfree((char *)(st->cached_includes[i]));
    ckfree((char *)(st->cached_includes));

    for(i = 0; i < st->nb_include_paths; i++)
        ckfree((char *)(st->include_paths[i]));
    ckfree((char *)(st->include_paths));

    for(i = 0; i < st->nb_sysinclude_paths; i++)
        ckfree((char *)(st->sysinclude_paths[i]));
    ckfree((char *)(st->sysinclude_paths));

    ckfree((char *)st);
}

int tcc_add_include_path(TCCState *st, const char *pathname)
{
    char *pathname1;
    
    pathname1 = tcc_strdup(st, pathname);
    dynarray_add(st, (void ***)&st->include_paths, &st->nb_include_paths, pathname1);
    return 0;
}

int tcc_add_sysinclude_path(TCCState *st, const char *pathname)
{
    char *pathname1;
    
    pathname1 = tcc_strdup(st, pathname);
    dynarray_add(st, (void ***)&st->sysinclude_paths, &st->nb_sysinclude_paths, pathname1);
    return 0;
}

static int tcc_add_file_internal(TCCState *st, const char *filename, int flags)
{
    const char *ext, *filename1;
    Elf32_Ehdr ehdr;
    Tcl_Channel fd;
    int ret;
    BufferedFile *saved_file;

    /* find source file type with extension */
    filename1 = strrchr(filename, '/');
    if (filename1)
        filename1++;
    else
        filename1 = filename;
    ext = strrchr(filename1, '.');
    if (ext)
        ext++;

    /* open the file */
    saved_file = file;
    file = tcc_open(st, filename);
    if (!file) {
        if (flags & AFF_PRINT_ERROR) {
            error_noabort(st, "file '%s' not found", filename);
        }
        ret = -1;
        goto fail1;
    }

    if (flags & AFF_PREPROCESS) ret = tcc_preprocess(st);
    else if (!ext || !strcmp(ext, "c")) {
        /* C file assumed */
        ret = tcc_compile(st);
    } else 
#ifdef CONFIG_TCC_ASM
    if (!strcmp(ext, "S")) {
        /* preprocessed assembler */
        ret = tcc_assemble(st, 1);
    } else if (!strcmp(ext, "s")) {
        /* non preprocessed assembler */
        ret = tcc_assemble(st, 0);
    } else 
#endif
#ifdef WIN32
    if (!strcmp(ext, "def")) {
        ret = pe_load_def_file(st, file->fd);
    } else
#endif
    {
        fd = file->fd;
        /* assume executable format: auto guess file type */
        ret = Tcl_Read(fd, (char *)&ehdr, sizeof(ehdr));
        Tcl_Seek(fd, 0, SEEK_SET);
        if (ret <= 0) {
            error_noabort(st, "could not read header");
            goto fail;
        } else if (ret != sizeof(ehdr)) {
            goto try_load_script;
        }

        if (ehdr.e_ident[0] == ELFMAG0 &&
            ehdr.e_ident[1] == ELFMAG1 &&
            ehdr.e_ident[2] == ELFMAG2 &&
            ehdr.e_ident[3] == ELFMAG3) {
            file->line_num = 0; /* do not display line number if error */
            if (ehdr.e_type == ET_REL) {
                ret = tcc_load_object_file(st, fd, 0);
            } else if (ehdr.e_type == ET_DYN) {
                if (st->output_type == TCC_OUTPUT_MEMORY) {
#ifdef WIN32
                    ret = -1;
#else
                    void *h;
                    h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
                    if (h)
                        ret = 0;
                    else
                        ret = -1;
#endif
                } else {
                    ret = tcc_load_dll(st, fd, filename, 
                                       (flags & AFF_REFERENCED_DLL) != 0);
                }
            } else {
                error_noabort(st, "unrecognized ELF file");
                goto fail;
            }
        } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
            file->line_num = 0; /* do not display line number if error */
            ret = tcc_load_archive(st, fd);
        } else 
#ifdef TCC_TARGET_COFF
        if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
            ret = tcc_load_coff(st, fd);
        } else
#endif
        {
            /* as GNU ld, consider it is an ld script if not recognized */
        try_load_script:
            ret = tcc_load_ldscript(st);
            if (ret < 0) {
                error_noabort(st, "unrecognized file type");
                goto fail;
            }
        }
    }
 the_end:
    tcc_close(file);
 fail1:
    file = saved_file;
    return ret;
 fail:
    ret = -1;
    goto the_end;
}

int tcc_add_file(TCCState *s, const char *filename)
{
    return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
}

int tcc_add_library_path(TCCState *s, const char *pathname)
{
    char *pathname1;
    
    pathname1 = tcc_strdup(s, pathname);
    dynarray_add(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname1);
    return 0;
}

/* find and load a dll. Return non zero if not found */
/* XXX: add '-rpath' option support ? */
static int tcc_add_dll(TCCState *s, const char *filename, int flags)
{
    char buf[1024];
    int i;



    for(i = 0; i < s->nb_library_paths; i++) {
        snprintf(buf, sizeof(buf), "%s/%s", 
                 s->library_paths[i], filename);
        if (tcc_add_file_internal(s, buf, flags) == 0)
            return 0;
    }
    return -1;
}

/* the library name is the same as the argument of the '-l' option */
int tcc_add_library(TCCState *s, const char *libraryname)
{
    char buf[1024];
    int i;
    
    /* first we look for the dynamic library if not static linking */
    if (!s->static_link) {
#ifdef WIN32
        snprintf(buf, sizeof(buf), "%s.def", libraryname);
#else
        snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
#endif
        if (tcc_add_dll(s, buf, 0) == 0) {
            return 0;
        }
    }

    /* then we look for the static library */
    for(i = 0; i < s->nb_library_paths; i++) {
        snprintf(buf, sizeof(buf), "%s/lib%s.a", 
                 s->library_paths[i], libraryname);
        if (tcc_add_file_internal(s, buf, 0) == 0)
            return 0;
    }
    return -1;
}

int tcc_add_symbol(TCCState *st, const char *name, unsigned long val)
{
    add_elf_sym(st, symtab_section, val, 0, 
                ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
                SHN_ABS, name);
    return 0;
}

int tcc_set_output_type(TCCState *s, int output_type)
{
    s->output_type = output_type;

    if (!s->nostdinc) {
        char buf[1024];

        /* default include paths */
        /* XXX: reverse order needed if -isystem support */
#ifndef WIN32
        tcc_add_sysinclude_path(s, "/usr/local/include");
        tcc_add_sysinclude_path(s, "/usr/include");
#endif
        snprintf(buf, sizeof(buf), "%s/include", Tcl_GetString(s->tcc_lib_path));
        tcc_add_sysinclude_path(s, buf);
#ifdef WIN32
        snprintf(buf, sizeof(buf), "%s/include/winapi", Tcl_GetString(s->tcc_lib_path));
        tcc_add_sysinclude_path(s, buf);
#endif
    }

    /* if bound checking, then add corresponding sections */
#if 0
    if (do_bounds_check) {
        /* define symbol */
        tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
        /* create bounds sections */
        bounds_section = new_section(s, ".bounds", 
                                     SHT_PROGBITS, SHF_ALLOC);
        lbounds_section = new_section(s, ".lbounds", 
                                      SHT_PROGBITS, SHF_ALLOC);
    }
#endif

    if (s->char_is_unsigned) {
        tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
    }

    /* add debug sections */
    if (do_debug) {
        /* stab symbols */
        stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
        stab_section->sh_entsize = sizeof(Stab_Sym);
        stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
        put_elf_str(s, stabstr_section, "");
        stab_section->link = stabstr_section;
        /* put first entry */
        put_stabs(s, "", 0, 0, 0, 0);
    }

    /* add libc crt1/crti objects */
#ifndef WIN32
    if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
        !s->nostdlib) {
        if (output_type != TCC_OUTPUT_DLL)
            tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
        tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
    }
#endif
    return 0;
}

#define WD_ALL    0x0001 /* warning is activated when using -Wall */
#define FD_INVERT 0x0002 /* invert value before storing */

typedef struct FlagDef {
    uint16_t offset;
    uint16_t flags;
    const char *name;
} FlagDef;

static const FlagDef warning_defs[] = {
    { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
    { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
    { offsetof(TCCState, warn_error), 0, "error" },
    { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
      "implicit-function-declaration" },
};

static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
                    const char *name, int value)
{
    int i;
    const FlagDef *p;
    const char *r;

    r = name;
    if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
        r += 3;
        value = !value;
    }
    for(i = 0, p = flags; i < nb_flags; i++, p++) {
        if (!strcmp(r, p->name))
            goto found;
    }
    return -1;
 found:
    if (p->flags & FD_INVERT)
        value = !value;
    *(int *)((uint8_t *)s + p->offset) = value;
    return 0;
}


/* set/reset a warning */
int tcc_set_warning(TCCState *s, const char *warning_name, int value)
{
    int i;
    const FlagDef *p;

    if (!strcmp(warning_name, "all")) {
        for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
            if (p->flags & WD_ALL)
                *(int *)((uint8_t *)s + p->offset) = 1;
        }
        return 0;
    } else {
        return set_flag(s, warning_defs, countof(warning_defs),
                        warning_name, value);
    }
}

static const FlagDef flag_defs[] = {
    { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
    { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
    { offsetof(TCCState, nocommon), FD_INVERT, "common" },
    { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
};

/* set/reset a flag */
int tcc_set_flag(TCCState *s, const char *flag_name, int value)
{
    return set_flag(s, flag_defs, countof(flag_defs),
                    flag_name, value);
}

/* extract the basename of a file */
static const char *tcc_basename(const char *name)
{
    const char *p;
    p = strrchr(name, '/');
#ifdef WIN32
    if (!p)
        p = strrchr(name, '\\');
#endif    
    if (!p)
        p = name;
    else 
        p++;
    return p;
}

#include "tcltcc.c"
